JavaScript - http://www.jellyfish.com/smacktv/channel/1

    * Collapse All
    * Expand All

http://www.jellyfish.com/smacktv/channel/1
http://www.jellyfish.com/javascripts/prototype.js

/*  Prototype JavaScript framework, version 1.5.0_rc0
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.0_rc0',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.inspect = function(object) {
  try {
    if (object == undefined) return 'undefined';
    if (object == null) return 'null';
    return object.inspect ? object.inspect() : object.toString();
  } catch (e) {
    if (e instanceof RangeError) return '...';
    throw e;
  }
}

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event);
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += (replacement(match) || '').toString();
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair = pairString.split('=');
      params[pair[0]] = pair[1];
      return params;
    });
  },

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

  inspect: function() {
    return "'" + this.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + "'";
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + (object[match[3]] || '').toString();
    });
  }
}

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
var Hash = {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
}

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    do {
      iterator(value);
      value = value.succ();
    } while (this.include(value));
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.options.method, this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) {
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
      this.dispatchException(e);
    }
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version,
       'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type', this.options.contentType);

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

  evalJSON: function() {
    try {
      return eval('(' + this.header('X-JSON') + ')');
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
        this.evalResponse();
    }

    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts)
      response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $() {
  var results = [], element;
  for (var i = 0; i < arguments.length; i++) {
    element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    results.push(Element.extend(element));
  }
  return results.length < 2 ? results[0] : results;
}

document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  return $A(children).inject([], function(elements, child) {
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(Element.extend(child));
    return elements;
  });
}

/*--------------------------------------------------------------------------*/

if (!window.Element)
  var Element = new Object();

Element.extend = function(element) {
  if (!element) return;
  if (_nativeExtensions) return element;

  if (!element._extended && element.tagName && element != window) {
    var methods = Element.Methods, cache = Element.extend.cache;
    for (property in methods) {
      var value = methods[property];
      if (typeof value == 'function')
        element[property] = cache.findOrStore(value);
    }
  }

  element._extended = true;
  return element;
}

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
}

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      Element[Element.visible(element) ? 'hide' : 'show'](element);
    }
  },

  hide: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = 'none';
    }
  },

  show: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = '';
    }
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
  },

  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
  },

  replace: function(element, html) {
    element = $(element);
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
  },

  getHeight: function(element) {
    element = $(element);
    return element.offsetHeight;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).include(className);
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).add(className);
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).remove(className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    for (var i = 0; i < element.childNodes.length; i++) {
      var node = element.childNodes[i];
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        Element.remove(node);
    }
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  childOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
  },

  getStyle: function(element, style) {
    element = $(element);
    var value = element.style[style.camelize()];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css.getPropertyValue(style) : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style.camelize()];
      }
    }

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';

    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (var name in style)
      element.style[name.camelize()] = style[name];
  },

  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = '';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = 'none';
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element._overflow = element.style.overflow;
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
  },

  undoClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element.style.overflow = element._overflow;
    element._overflow = undefined;
  }
}

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if(!HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  var HTMLElement = {}
  HTMLElement.prototype = document.createElement('div').__proto__;
}

Element.addMethods = function(methods) {
  Object.extend(Element.Methods, methods || {});

  if(typeof HTMLElement != 'undefined') {
    var methods = Element.Methods, cache = Element.extend.cache;
    for (property in methods) {
      var value = methods[property];
      if (typeof value == 'function')
        HTMLElement.prototype[property] = cache.findOrStore(value);
    }
    _nativeExtensions = true;
  }
}

Element.addMethods();

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toLowerCase();
        if (tagName == 'tbody' || tagName == 'tr') {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set(this.toArray().concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
    }).join(' '));
  },

  toString: function() {
    return this.toArray().join(' ');
  }
}

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }

    if (this.expression == '')  abort('empty expression');

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }

    if (expr == '*') return this.params.wildcard = true;

    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case '':
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }

    if (expr.length > 0) abort(expr.inspect());
  },

  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;

    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.id == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0; i < clause.length; i++)
        conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }

        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push(value + ' != null'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }

    return conditions.join(' && ');
  },

  compileMatcher: function() {
    this.match = new Function('element', 'if (!element.tagName) return false; \
      return ' + this.buildMatchExpression());
  },

  findElements: function(scope) {
    var element;

    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];

    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

    var results = [];
    for (var i = 0; i < scope.length; i++)
      if (this.match(element = scope[i]))
        results.push(Element.extend(element));

    return results;
  },

  toString: function() {
    return this.expression;
  }
}

function $$() {
  return $A(arguments).map(function(expression) {
    return expression.strip().split(/\s+/).inject([null], function(results, expr) {
      var selector = new Selector(expr);
      return results.map(selector.findElements.bind(selector)).flatten();
    });
  }).flatten();
}
var Field = {
  clear: function() {
    for (var i = 0; i < arguments.length; i++)
      $(arguments[i]).value = '';
  },

  focus: function(element) {
    $(element).focus();
  },

  present: function() {
    for (var i = 0; i < arguments.length; i++)
      if ($(arguments[i]).value == '') return false;
    return true;
  },

  select: function(element) {
    $(element).select();
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
  }
}

/*--------------------------------------------------------------------------*/

var Form = {
  serialize: function(form) {
    var elements = Form.getElements($(form));
    var queryComponents = new Array();

    for (var i = 0; i < elements.length; i++) {
      var queryComponent = Form.Element.serialize(elements[i]);
      if (queryComponent)
        queryComponents.push(queryComponent);
    }

    return queryComponents.join('&');
  },

  getElements: function(form) {
    form = $(form);
    var elements = new Array();

    for (var tagName in Form.Element.Serializers) {
      var tagElements = form.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    }
    return elements;
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name)
      return inputs;

    var matchingInputs = new Array();
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) ||
          (name && input.name != name))
        continue;
      matchingInputs.push(input);
    }

    return matchingInputs;
  },

  disable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.blur();
      element.disabled = 'true';
    }
  },

  enable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.disabled = '';
    }
  },

  findFirstElement: function(form) {
    return Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    Field.activate(Form.findFirstElement(form));
  },

  reset: function(form) {
    $(form).reset();
  }
}

Form.Element = {
  serialize: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

      if (parameter[1].constructor != Array)
        parameter[1] = [parameter[1]];

      return parameter[1].map(function(value) {
        return key + '=' + encodeURIComponent(value);
      }).join('&');
    }
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter)
      return parameter[1];
  }
}

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return Form.Element.Serializers.textarea(element);
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
    }
    return false;
  },

  inputSelector: function(element) {
    if (element.checked)
      return [element.name, element.value];
  },

  textarea: function(element) {
    return [element.name, element.value];
  },

  select: function(element) {
    return Form.Element.Serializers[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var value = '', opt, index = element.selectedIndex;
    if (index >= 0) {
      opt = element.options[index];
      value = opt.value || opt.text;
    }
    return [element.name, value];
  },

  selectMany: function(element) {
    var value = [];
    for (var i = 0; i < element.length; i++) {
      var opt = element.options[i];
      if (opt.selected)
        value.push(opt.value || opt.text);
    }
    return [element.name, value];
  }
}

/*--------------------------------------------------------------------------*/

var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    var elements = Form.getElements(this.element);
    for (var i = 0; i < elements.length; i++)
      this.registerCallback(elements[i]);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        case 'password':
        case 'text':
        case 'textarea':
        case 'select-one':
        case 'select-multiple':
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    this._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      element.detachEvent('on' + name, observer);
    }
  }
});

/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  clone: function(source, target) {
    source = $(source);
    target = $(target);
    target.style.position = 'absolute';
    var offsets = this.cumulativeOffset(source);
    target.style.top    = offsets[1] + 'px';
    target.style.left   = offsets[0] + 'px';
    target.style.width  = source.offsetWidth + 'px';
    target.style.height = source.offsetHeight + 'px';
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      valueT -= element.scrollTop  || 0;
      valueL -= element.scrollLeft || 0;
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';;
    element.style.left   = left + 'px';;
    element.style.width  = width + 'px';;
    element.style.height = height + 'px';;
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}

http://www.jellyfish.com/javascripts/json.js

/*
    json.js
    2007-01-10

    This file adds these methods to JavaScript:

        array.toJSONString()
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString()
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2007.
*/
if (!Object.prototype.toJSONString) {
    Array.prototype.toJSONString = function () {
        var a = ['['], b, i, l = this.length, v;

        function p(s) {
            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'undefined':
            case 'function':
            case 'unknown':
                break;
            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;
            default:
                p(v.toJSONString());
            }
        }
        a.push(']');
        return a.join('');
    };

    Boolean.prototype.toJSONString = function () {
        return String(this);
    };

    Date.prototype.toJSONString = function () {

        function f(n) {
            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };

    Number.prototype.toJSONString = function () {
        return isFinite(this) ? String(this) : "null";
    };

    Object.prototype.toJSONString = function () {
        var a = ['{'], b, i, v;

        function p(s) {
            if (b) {
                a.push(',');
            }
            a.push(i.toJSONString(), ':', s);
            b = true;
        }

        for (i in this) {
            if (this.hasOwnProperty(i)) {
                v = this[i];
                switch (typeof v) {
                case 'undefined':
                case 'function':
                case 'unknown':
                    break;
                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;
                default:
                    p(v.toJSONString());
                }
            }
        }
        a.push('}');
        return a.join('');
    };


    (function (s) {
        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        s.parseJSON = function (filter) {
            try {
                if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                        test(this)) {
                    var j = eval('(' + this + ')');
                    if (typeof filter === 'function') {
                        function walk(k, v) {
                            if (v && typeof v === 'object') {
                                for (var i in v) {
                                    if (v.hasOwnProperty(i)) {
                                        v[i] = walk(i, v[i]);
                                    }
                                }
                            }
                            return filter(k, v);
                        }
                        return walk('', j);
                    }
                    return j;
                }
            } catch (e) {
            }
            // throw new SyntaxError("parseJSON");
        };

        s.toJSONString = function () {
            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                    var c = m[b];
                    if (c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}

http://www.jellyfish.com/smack/javascripts/sugar.js

/*
	Copyright Douglas Crockford
	http://www.crockford.com/javascript/inheritance.html
*/

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

Function.method('inherits', function (parent) {
    var d = {}, p = (this.prototype = new parent());
    this.method('uber', function uber(name) {
        if (!(name in d)) {
            d[name] = 0;
        }        
        var f, r, t = d[name], v = parent.prototype;
        if (t) {
            while (t) {
                v = v.constructor.prototype;
                t -= 1;
            }
            f = v[name];
        } else {
            f = p[name];
            if (f == this[name]) {
                f = v[name];
            }
        }
        d[name] += 1;
        r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
        d[name] -= 1;
        return r;
    });
    return this;
});

Function.method('swiss', function (parent) {
    for (var i = 1; i < arguments.length; i += 1) {
        var name = arguments[i];
        this.prototype[name] = parent.prototype[name];
    }
    return this;
});

http://www.jellyfish.com/smack/javascripts/deal/Dealometer.js

DealOMeter = function(startTime, now, endTime, price)
{
	this.startTime = new Date(startTime);
	this.now = new Date(now);
	this.endTime = new Date(endTime);
	this.price = price;
		
	this.guruGuess = 23;
	this.guruNotPassed = true;		
	this.sliderPosition = Math.round((100 * (this.now.getTime() - this.startTime.getTime())) / (this.endTime.getTime() - this.startTime.getTime()) * 100) / 100;
	this.totalMiliseconds = this.endTime.getTime() - this.startTime.getTime();
	
	//Set timer period to 10 times a second (100ms) for everyone 'cept IE6
	//if ( typeof document.body.style.maxHeight != "undefined" )
		//this.timerPeriod = 100;
	//else //IE 6
		this.timerPeriod = 1000;
	
	this.sliderDeltaV = (this.timerPeriod * 100) / this.totalMiliseconds;
	this.sliderTimer;
	
	this.initialize = function()
	{
	  this.positionSlider();							
		this.start();
	}
	
	this.start = function()
	{
		window.dealometer_timer = setInterval(this.moveSliderCache.bind(this), this.timerPeriod);
	}
	
	this.cleanUp = function()
	{
		clearInterval(window.dealometer_timer);
	}
		
	this.moveSlider = function()
	{
		this.sliderPosition = this.sliderPosition + this.sliderDeltaV;
		this.positionSlider();
	}
	
	this.moveSliderCache = this.moveSlider;
}

DealOMeter.prototype.positionSlider = function() {
   if((this.sliderPosition > 0)&&(this.sliderPosition <= 100)) {
		document.getElementById("slider").style.top = Math.abs(this.sliderPosition).toFixed(2) + "%";
		document.getElementById("greyRuler").style.height = Math.abs(this.sliderPosition).toFixed(2) + "%";		
		document.getElementById("slider").innerHTML = Math.abs(this.sliderPosition).toFixed(2) + "% off";				
		document.getElementById("slider").style.display = "block";
		document.getElementById("retailPrice").innerHTML = "$" + Math.abs(this.price).toFixed(2);
		document.getElementById("cashBack").innerHTML = "$" + (this.price * (this.sliderPosition *.01)).toFixed(2);
		document.getElementById("totalCost").innerHTML = "$" + Math.abs(this.price * (1-(this.sliderPosition *.01))).toFixed(2);	
	} else if(this.sliderPosition > 100) {
		document.getElementById("slider").style.top = "100%";
		document.getElementById("greyRuler").style.height = "100%";		
		document.getElementById("slider").innerHTML = "100% off";		
		document.getElementById("retailPrice").innerHTML = "$" + Math.abs(this.price).toFixed(2);
		document.getElementById("cashBack").innerHTML = "$" + Math.abs(this.price).toFixed(2);
		document.getElementById("totalCost").innerHTML = "$0.00";	
	} else if(this.sliderPosition > 100) {
		document.getElementById("slider").style.top = "0%";
		document.getElementById("greyRuler").style.height = "0%";		
		document.getElementById("slider").innerHTML = "0% off";		
		document.getElementById("retailPrice").innerHTML = "$" + Math.abs(this.price).toFixed(2);
		document.getElementById("cashBack").innerHTML = "$0.00";
		document.getElementById("totalCost").innerHTML = "$" + Math.abs(this.price).toFixed(2);	
	}
}

http://www.jellyfish.com/smack/javascripts/Segment.js

Segment = function(json_hash) {
	for(var i in json_hash) {
		this[i] = json_hash[i];
	}
}

function secondsRemaining(startedAt, currentTime, durationInSeconds) {
  var x = (startedAt + durationInSeconds*1000 - currentTime)/1000; // use when durations are really in secondss
  // var x = (startedAt + durationInSeconds*60000 - currentTime)/1000;
  // console.log(startedAt + " " + durationInSeconds*60000 + " " + currentTime);
  // console.log(x);
  return x;
}


http://www.jellyfish.com/smack/javascripts/HypertextTemplate.js

HypertextTemplate = function(myArray)
{
	this.template = myArray;
	this.pointers = new Array();
	this.makePointers();
}
	
HypertextTemplate.prototype.renderHTML = function()
{
	return this.template.join("");
}
	
HypertextTemplate.prototype.update = function(updateThis, withThisText)
{
  // console.log("replacing: " + updateThis + " with " + withThisText);
	this.template[this.pointers[updateThis]] = withThisText;
}
	
HypertextTemplate.prototype.makePointers = function()
{
	for( var i = 0; i < this.template.length; i++ )
		if ( this.template[i].match(/^__/) )
			this.pointers[this.template[i].replace(/^__/, "")] = i;
}

http://www.jellyfish.com/smack/javascripts/deal/LiveDeal.js

LiveDeal = function(json_hash)
{	
	this.typeIdentifier = "LiveDeal";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate(["<div id=\"dealHeader\"><ul id=\"dealMenu\"><li><a href=\"javascript:toggleCountDown();\" title=\"Countdown\" id=\"countdownMenu\" class=\"highlighted\"></a></li><li><a href=\"javascript:toggleDetails();\" title=\"Product Details\" id=\"productMenu\"></a></li><li><a href=\"javascript:toggleHowToPlay();\" title=\"How to Play\" id=\"playMenuDeal\"></a></li></ul></div><div id=\"deal\"><div id=\"countdown\"><div id=\"dealDetails\"><div id=\"itemPhoto\"><a id=\"productImageAnchor\" href=\"","__productURL1","\" target=\"new\"><img src=\"","__productImageURL","\" alt=\"","__productNameAlt","\" id=\"productImage\" /></a><div id=\"storeContainer\"><span id=\"shippedFromLabel\">Shipped From</span><a id=\"storeAnchor\" href=\"","__storeURL","\" target=\"new\"><img src=\"","__storeImageURL","\" alt=\"","__storeName","\" id=\"storeImage\" /></a></div></div><div id=\"dealHowTo\" style=\"display:none;\"><h2>How To Play</h2><h3>A Test of Timing</h3><p>You're watching a live Smack Shopping deal. Although it may look complicated, it's pretty simple. Each Smack auction includes a hidden quantity of product. Every second, the price of the product drops. The longer you wait, the better the deal gets, but if you wait too long the deal will sell out and you'll miss out.</p><h3>Ready to Buy?</h3><p>When you're ready to buy, just click on the Buy button and fill out your order info to complete your order and lock in the final price you will pay.  Once you lock in your final price on a product, we bill your credit card, process your order, and have one of our suppliers ship the product to you.</p><h3>You Can Still Play Without Buying!</h3><p>Even if you don't buy, you can still have a great time playing the Smack guru guess game, setting up your shopping profile, and chatting along with the rest of the Smack community. You'll never think about shopping online by yourself again!</p><p>For More Information, Visit <a href=\"/smacktv/faq\">How This Works</a></p></div><h2 id=\"dealProductName\"><a id=\"productNameAnchor\" href=\"","__productURL2","\" target=\"new\">","__productName","</a></h2><div id=\"productDetails\">","__productDetails","</div><div id=\"pills\"><div class=\"pillLeft\">Starting Price*<div id=\"retailPrice\"></div></div><div class=\"pillRight\">Your Savings<div id=\"cashBack\"></div></div><div class=\"clearFloat\"> </div></div><div><div id=\"pill\">Final Price<div id=\"totalCost\"></div><span>*includes tax and shipping</span></div></div><a href=\"","__buyNowURL","\" title=\"Buy Now\" id=\"buyNow\" target=\"new\"></a></div></div><div id=\"ruler\"><div id=\"sliderContainer\"><div id=\"slider\"></div><div id=\"guruIndicator\" class=\"guruBad\"><img src=\"/smack/images/smacktv/deal/my_guess","__guruImage","\" alt=\"My Guess\" /></div><div id=\"greyRuler\"></div></div></div><div class=\"clearFloat\"></div></div></div>"]);

	this.startTime = new Date(this.startedAt);
 	this.rightNow = new Date(this.currentTime);
 	// this.endTime = new Date(this.startedAt + (this.duration * 60000));
 	this.endTime = new Date(this.startedAt + (this.duration * 1000));
 	this.dealometer = new DealOMeter(this.startTime, this.rightNow, this.endTime, this.offering.price);
 	this.draw();
 	
 	if (this.merchant.jfDirect != null && this.merchant.jfDirect == true)  {
 
 		$('storeAnchor').style.display = 'none';
 		$('shippedFromLabel').style.display = 'none';
 		i = new Image();
 		i.id = "storeImage";
 		if (this.merchant.imageUri != null)
	 		i.src = "http://www.jellyfish.com/img" + this.merchant.imageUri;
	 	else
	 		i.src = "/smack/images/smacktv/deal/noMerchant.gif";
	 	$('storeContainer').appendChild(i);
	
		$('productImage').src = "/img" + this.product.imageUri; 	
		$('productImageAnchor').href = this.product.productUrl;	
		$('productNameAnchor').href = this.product.productUrl;
 	}
 	
}

LiveDeal.prototype.draw = function()
{

	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
		return;
	else
	{
		globalCleanUp();
		window.liveObject = this;
	}

	var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	if (this.sponsor != null)  {
		var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor.type == "c")  {
			$("logosContainer").innerHTML = sponsorHTML;
		} else  {
			$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
		}
	} else  {
		$("logosContainer").innerHTML = noSponsorHTML;
	}
	
	if(this.segmentSponsor != null)  {
		if (this.segmentSponsor.logoUri.match(/.swf/) == null)
			$('segmentSponsorContainer').innerHTML = '<br/><a href="/redirect/outbound?u=' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
		else
			$('segmentSponsorContainer').innerHTML = '<br/><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object>';
		$('segmentSponsorContainer').style.display = '';
	} else  {
		$('segmentSponsorContainer').style.display = 'none';
		$('segmentSponsorContainer').innerHTML = '';
	}
	
	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}


	if ( typeof document.body.style.maxHeight != "undefined" )
		this.template.update("guruImage", ".gif");
	else
		this.template.update("guruImage", ".png");
	
	document.getElementById("messageCenter").className = "messageLiveDeal";

	this.template.update("productURL1", "/products/offerings/" + this.product.categoryId + "/" + this.product.id);
	this.template.update("productImageURL", "http://www.jellyfish.com/img" + this.product.imageUri);
	this.template.update("productNameAlt", this.product.name); 
	this.template.update("storeURL", "/users/signup?c=" + this.merchant.id);
  
	if (this.merchant.imageUri == "null")
		this.template.update("storeImageURL", "/smack/images/smacktv/deal/noMerchant.gif"); 
	else
		this.template.update("storeImageURL", "http://www.jellyfish.com/img" + this.merchant.imageUri); 
  	
	this.template.update("storeName", this.merchant.name); 
	this.template.update("productURL2", "/products/offerings/" + this.product.categoryId + "/" + this.product.id);  
	this.template.update("productName", this.product.name);

/*
	if (this.offering.shippingCost == 0)
	{
		this.template.update("shipping", "Free");
	}
	else if (this.offering.maxShippingCost)
	{
		this.template.update("shipping", "$" + this.offering.shippingCost.toFixed(2) + " - " + this.offering.maxShippingCost.toFixed(2));
	}
	else
	{
		this.template.update("shipping", "$" + this.offering.shippingCost.toFixed(2));
	}
*/

	this.template.update("buyNowURL", (window.secureBuyUrl || "") + "/smacktv/buy/" + this.id);
  
	this.template.update("productDetails", this.product.description);  
  
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
  
	//get rendered height and assign to min-height (minus 30px padding) for switching to a terse detail view
	//document.getElementById("deal").style.minHeight = (document.getElementById("deal").offsetHeight - 30) + "px";
  
	this.dealometer.initialize();
	
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">Countdown ends when quantity sells out</div><div class="timerText" id="election_timer"></div>';
}

LiveDeal.prototype.cleanUp = function()
{
	this.dealometer.cleanUp();
}

toggleClass = function(myId, myClass)
{
	document.getElementById(myId).className = myClass;
}

toggleCountDown = function()
{
	document.getElementById("itemPhoto").style.display = "block";
	document.getElementById("pills").style.display = "block";
	document.getElementById("productDetails").style.display = "none";
	document.getElementById("dealHowTo").style.display = "none";
	document.getElementById("productMenu").className = "unhighlighted";
	document.getElementById("countdownMenu").className = "highlighted";
	document.getElementById("playMenuDeal").className = "unhighlighted";
	document.getElementById("dealProductName").style.display = "block";
}

toggleDetails = function()
{
	document.getElementById("itemPhoto").style.display = "none";
	document.getElementById("pills").style.display = "none";
	document.getElementById("productDetails").style.display = "block";
	document.getElementById("dealHowTo").style.display = "none";
	document.getElementById("productMenu").className = "highlighted";
	document.getElementById("countdownMenu").className = "unhighlighted";
	document.getElementById("playMenuDeal").className = "unhighlighted";
	document.getElementById("dealProductName").style.display = "block";
}

toggleHowToPlay = function()
{
	document.getElementById("itemPhoto").style.display = "none";
	document.getElementById("pills").style.display = "none";
	document.getElementById("productDetails").style.display = "none";
	document.getElementById("dealHowTo").style.display = "block";
	document.getElementById("productMenu").className = "unhighlighted";
	document.getElementById("countdownMenu").className = "unhighlighted";
	document.getElementById("playMenuDeal").className = "highlighted";
	document.getElementById("dealProductName").style.display = "none";
}

http://www.jellyfish.com/smack/javascripts/deal/SoldOutDeal.js

SoldOutDeal = function(json_hash)
{
	this.typeIdentifier = "SoldOutDeal";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
		this.template = new HypertextTemplate(["<div id=\"deal\"><div id=\"dealDetails\"><div id=\"soldOutPhoto\"><a id=\"productImageAnchor\" href=\"","__productURL","\" target=\"new\"><img src=\"","__productImageURL","\" alt=\"","__productNameAlt","\" id=\"productImage\" /></a><div id=\"soldOutImage\"><div id=\"soldOutNumbers\">","__numberSold","</div><img src=\"/smack/images/smacktv/deal/soldout.gif\" style=\"clear:both;\" alt=\"Sold Out\" /></div></div><h2 id=\"dealProductName\"><a id=\"productNameAnchor\" href=\"","__productURL2","\" target=\"new\">","__productName","</a></h2></div><div id=\"bestDeal\"><a href=\"", "__shoppingPageLink", "\"><img src=\"","__bestAvatar","\" alt=\"","__bestUserNameAlt","\" style=\"border: 0px;\" />","__bestUserName","</a><span class=\"percentOff\">","__bestPercent","%</span>Discount</div><div class=\"clearFloat\"> </div><div id=\"bestDeals\"><img src=\"/smack/images/smacktv/deal/best_deals.gif\" alt=\"Best Deals\" /><table cellpadding=\"0\" cellspacing=\"0\"><tr class=\"dealTableHeader\"><td>Rank</td><td>Nickname</td><td>Location</td><td>Discount</td></tr>","__bestTable","</table></div></div>"]);
	
	this.draw();
	
 	if (this.merchant.jfDirect != null && this.merchant.jfDirect == true)  {

		$('productImage').src = "/img" + this.product.imageUri; 	
		$('productImageAnchor').href = this.product.productUrl;	
		$('productNameAnchor').href = this.product.productUrl;
	
 	}
	
}

SoldOutDeal.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
		return;
	else
	{
		globalCleanUp();
		window.liveObject = this;
		this.initializeTimer();
	}
	
	var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	if (this.sponsor != null)  {
		var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor.type == "c")  {
			$("logosContainer").innerHTML = sponsorHTML;
		} else  {
			$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
		}
	} else  {
		$("logosContainer").innerHTML = noSponsorHTML;
	}
	
	if(this.segmentSponsor != null)  {
		if (this.segmentSponsor.logoUri.match(/.swf/) == null)
			$('segmentSponsorContainer').innerHTML = '<br/><a href="/redirect/outbound?u=' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
		else
			$('segmentSponsorContainer').innerHTML = '<br/><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object>';
		$('segmentSponsorContainer').style.display = '';
	} else  {
		$('segmentSponsorContainer').style.display = 'none';
		$('segmentSponsorContainer').innerHTML = '';
	}
	
	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}

	document.getElementById("messageCenter").className = "messageSoldOutDeal";
	
	this.template.update("productURL", "/products/offerings/" + this.product.categoryId + "/" + this.product.id);
	this.template.update("productImageURL", "http://www.jellyfish.com/img" + this.product.imageUri);
	this.template.update("productNameAlt", this.product.name);
	this.template.update("productURL2", "/products/offerings/" + this.product.categoryId + "/" + this.product.id);
	this.template.update("productName", this.product.name);
	
	if (this.quantitySold == 0)
	{
		this.template.update("numberSold", "<img src=\"/smack/images/smacktv/deal/soldout/0.gif\" alt=\"0\" />");
		document.getElementById("liveObjectContainer").className = "noOneBought";
		this.template.update("bestTable", "<tr class=\"highlight\"><td colspan=\"4\">Oops, no one bought this product.</td></tr>");
	}
	else
	{
		var tempNumbersString = "";
		var tempSoldOut = this.quantitySold.toString().split('');
		for (var n = 0; n < tempSoldOut.length; n++) {
			tempNumbersString += "<img src=\"/smack/images/smacktv/deal/soldout/" + tempSoldOut[n] + ".gif\" alt=\"" + tempSoldOut[n] + "\" />"
		}
		this.template.update("numberSold", tempNumbersString);
		
		this.template.update("bestPrice", (this.offering.price - ((this.bestDeals[0].discount * .01) * this.offering.price)).toFixed(2));
		this.template.update("bestAvatar", this.bestDeals[0].avatarUri);
		this.template.update("shoppingPageLink", "/shoppers/" + this.bestDeals[0].shopperPageName);
		this.template.update("bestUserNameAlt", this.bestDeals[0].nickname);
		this.template.update("bestUserName", this.bestDeals[0].nickname);
		this.template.update("bestPercent", this.bestDeals[0].discount.toFixed(2));
		
		var winnerTable = new Array();
		if ( this.bestDeals.length != 0)
		{
			for(var i = 0; i < this.bestDeals.length; i++)
			{
				if ( i % 2 != 0)
					tableHighlight = "";
				else
					tableHighlight = " class=\"highlight\"";

				winnerTable.push("<tr" + tableHighlight + "><td class=\"rank\">" + this.bestDeals[i].rank + "</td><td><a target=\"_blank\" href=\"/shoppers/" + this.bestDeals[i].shopperPageName + "\">" + this.bestDeals[i].nickname + "</a></td><td>" + this.bestDeals[i].city + ", " + this.bestDeals[i].state + "</td><td class=\"guess\">" + this.bestDeals[i].discount.toFixed(2) + "%</td></tr>");
			}	
			this.template.update("bestTable", winnerTable.join(""));
		}
		else
		{
			this.template.update("bestTable", "<tr class=\"highlight\"><td colspan=\"4\">Oops, no one guessed correctly.</td></tr>");
		}
	}
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
	
}


SoldOutDeal.prototype.initializeTimer = function() {

if (this.nextSegmentType == "deal")
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">Next Deal Starts In:</div><div class="timerText" id="sold_out_deal_timer"></div>';
}
else if (this.nextSegmentType == "outwit")
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">Outwit Starts In:</div><div class="timerText" id="sold_out_deal_timer"></div>';
}
else if (this.nextSegmentType == "wheel")
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">The Smack Wheel Spins In:</div><div class="timerText" id="sold_out_deal_timer"></div>';
}
else
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">The Show Ends In:</div><div class="timerText" id="sold_out_deal_timer"></div>';
}

  window.sold_out_deal_timer = new FlashTimer('sold_out_deal_timer', secondsRemaining(this.soldOutAt, this.currentTime, this.duration));
  window.sold_out_deal_timer.startTimer();
}


SoldOutDeal.prototype.cleanUp = function()
{
  window.sold_out_deal_timer.cleanUp();
	document.getElementById("liveObjectContainer").removeAttribute("class"); 
}

http://www.jellyfish.com/smack/javascripts/smack_wheel/LiveSmackWheel.js

LiveSmackWheel = function(json_hash, segmentID)
{
	this.typeIdentifier = "LiveSmackWheel";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.segment = segmentID;
	
	this.template = new HypertextTemplate(["<div id=\"wheelHeader\" class=\"wheel\"><ul id=\"smackWheelMenu\"><li><a href=\"javascript:toggleClass('wheelHeader','wheel');toggleClass('deal','wheel');\" title=\"Smackwheel\" id=\"wheelMenu\" class=\"highlighted\"></a></li><li><a href=\"javascript:toggleClass('wheelHeader','odds');toggleClass('deal','odds');\" title=\"Prizes and Odds\" id=\"oddsMenu\"></a></li><li><a href=\"javascript:toggleClass('wheelHeader','play');toggleClass('deal','play');\" title=\"How To Play\" id=\"playMenu\"></a></li></ul></div><div id=\"deal\" class=\"wheel\"><div id=\"wheelOdds\">Odds</div><div id=\"wheelPlay\"><h2>How To Play</h2><h3>SmackWheel</h3><p>Where the thrill of a game show meets the Internet, the SmackWheel is the Internet's first spinning wheel of goodies that is viewed by a live online audience.</p><h3>Best Guru Guesser Gets to Spin</h3><p>The person who made the best guess on the previous Smack deal (closest to without going over) gets to stop the Wheel and win a prize.</p><h3>Don't Guess and Leave</h3><p>If you win the Guru guess and don't stop the Wheel, you'll bust (aka Moose) and lose out on your chance to win a prize.</p><h3>Guru Points</h3><p>Guru points are awarded to the top 10 guessers on each deal-9 points to the best guesser and 3 points each for guessers 2-10. Guru points not only give you extra \"street cred\" with the Smack, they also give you a chance to win a prize in our monthly guru points race.</p><h3>Past Winners</h3><p>Past Wheel winners and prizes are listed under the <a href=\"/smacktv/archive\">Past Deals</a> tab.</p></div><div id=\"","__wheelType","\">","__stopWheelLink","<div id=\"v2WheelContainer\"></div><div id=\"spinnerInfo\"><img src=\"", "__avatarUri", "\" alt=\"","__winnerNickAlt","\"/><div class=\"name\"><a href=\"/shoppers/","__winnerNickLink","\" target=\"_blank\">","__winnerNick","</a>","__spinnerCity", ", ", "__spinnerState","<br /><br />member since<br />", "__winnerMemberSince", "</div><div class=\"clearFloat\"> </div></div><div id=\"wheelInfoDiv\"><table cellpadding=\"0\" cellspacing=\"0\" id=\"wheelInfoTable\"><tr class=\"highlight\"><td>Guru Points:</td><td>","__guruPoints","</td></tr><tr><td>My Page Visits:</td><td>","__profileVisits","</td></tr><tr class=\"highlight\"><td>Attendance:</td><td>","__attendancePct","</td></tr><tr><td>JF Purchases:</td><td>","__jfPurchaseCount","</td></tr><tr class=\"highlight\"><td>Smack Purchases:</td><td>","__smackPurchaseCount","</td></tr><tr><td>Wheel Spins:</td><td>","__wheelSpins","</td></tr><tr class=\"highlight\"><td>Comment Count:</td><td>","__commentCount","</td></tr></table></div><img id=\"vitalsBottom\" src=\"/smack/images/smacktv/wheel/vitals_bottom.gif\" id=\"vitalsBottom\" alt=\"\" /><div id=\"wheelMessage\"><div id=\"wheelMessageHighlight\"></div></div><div id=\"muteContainer\"><a id=\"mute_sound_toggle\" class=\"","__wheelMuteClass","\" \"href=\"#\" onclick=\"javascript:window.SmackWheel.toggleMuteSound(); return false;\" title=\"Toggle Sound\"></a></div></div></div>"]);
	
	this.draw();
}

LiveSmackWheel.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
	{	
		return;
	}
	else
	{
	
	
	var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	if (this.sponsor != null)  {
		var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor.type == "c")  {
			$("logosContainer").innerHTML = sponsorHTML;
		} else  {
			$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
		}
	} else  {
		$("logosContainer").innerHTML = noSponsorHTML;
	}

	if(this.segmentSponsor != null)  {
		if (this.segmentSponsor.logoUri.match(/.swf/) == null)
			$('segmentSponsorContainer').innerHTML = '<br/><a href="/redirect/outbound?u=' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
		else
			$('segmentSponsorContainer').innerHTML = '<br/><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object>';
		$('segmentSponsorContainer').style.display = '';
	} else  {
		$('segmentSponsorContainer').style.display = 'none';
		$('segmentSponsorContainer').innerHTML = '';
	}
	
	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}
		globalCleanUp();
		window.liveObject = this;
		if(this.contestant_token) {
		  document.getElementById("messageCenter").innerHTML = '<div class="messageText">You must stop the wheel in</div><div class="timerText" id="live_smack_wheel_timer"></div>';
		} else {
		  if(this.contestant) { 
    		document.getElementById("messageCenter").innerHTML = '<div class="messageText">' + this.contestant.nickname + ' must stop the wheel in</div><div class="timerText" id="live_smack_wheel_timer"></div>';
  		} else {	  	  
    		document.getElementById("messageCenter").innerHTML = '<div class="messageText">The spinner must stop the wheel in</div><div class="timerText" id="live_smack_wheel_timer"></div>';
		  }
		}
	  	window.live_smack_wheel_timer = new FlashTimer('live_smack_wheel_timer', secondsRemaining(this.startedAt, this.currentTime, this.duration), { endText: "Oh no!" });
  		window.live_smack_wheel_timer.startTimer();
	}
	
	if (!window.mute)
		this.template.update("wheelMuteClass", "wheelMute");
	else
		this.template.update("wheelMuteClass", "wheelUnMute");
	
	if (this.contestant_token)
	{
		this.template.update("wheelType", "wheelContestant");
		this.template.update("stopWheelLink", "<img src=\"/smack/images/good_luck.gif\" alt=\"Good Luck!\" /><a href=\"#\" id=\"wheelStopButton\" title=\"Stop the wheel!\" onclick=\"this.className='stopped';new Ajax.Request('/smacktv/stopWheel/" + this.segment + "', {asynchronous:true, evalScripts:true, parameters:''}); return false;\"></a>");
	}
	else
	{
		this.template.update("wheelType", "wheelAudience");
		this.template.update("stopWheelLink", "");
	}
	
	if (this.contestant)
	{
		if (this.contestant.city != "null")
		{
			this.template.update("spinnerCity", this.contestant.city);
			this.template.update("spinnerState", this.contestant.state);
		}
		else
		{
			this.template.update("spinnerCity", "Nowheresville");
			this.template.update("spinnerState", "NP");
		}
		
		this.template.update("wheelSpins", this.contestant.spinCount);
	
		this.template.update("winnerNickAlt",  this.contestant.nickname);
		this.template.update("winnerNickLink",  this.contestant.shopperPageName);
		this.template.update("winnerNick",  this.contestant.nickname);
		this.template.update("winnerMemberSince", this.contestant.memberSinceDate);
		this.template.update("profileVisits",  this.contestant.profileVisits);
		this.template.update("attendancePct",  this.contestant.attendancePct+"%");
		this.template.update("jfPurchaseCount",  this.contestant.jfPurchaseCount);
		this.template.update("smackPurchaseCount",  this.contestant.smackPurchaseCount);
		this.template.update("guruPoints",  this.contestant.guruPoints);
		this.template.update("commentCount",  this.contestant.commentCount);
		this.template.update("avatarUri", this.contestant.avatarUri);
	}
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
	
	window.SmackWheel = new SmackWheelV2();
	window.SmackWheel.drawWheel("v2WheelContainer", this.prizes, this.slowdown_factor);
	window.SmackWheel.startWheel();
	
	if( (window.SmackWheel) ) {
	  this.drawOdds();
	}
	
	document.getElementById("messageCenter").className = "messageLiveSmackWheel";
}

LiveSmackWheel.prototype.drawOdds = function() {
  h  = "<ul id=\"wheelOddsList\">";
  for(var p=0; p < window.SmackWheel.odds.length; p++) {
    h += "<li><b>" + window.SmackWheel.odds[p].name + " (" + window.SmackWheel.odds[p].odds + "%)</b><br />" + window.SmackWheel.odds[p].description + "</li>"
  }
  h += "</ul>";
  $('wheelOdds').innerHTML = h;
}



LiveSmackWheel.prototype.cleanUp = function()
{
	window.live_smack_wheel_timer.cleanUp();
	document.getElementById("liveObjectContainer").removeAttribute("class"); 
}





http://www.jellyfish.com/smack/javascripts/smack_wheel/StoppedSmackWheel.js

StoppedSmackWheel = function(json_hash)
{
	this.typeIdentifier = "StoppedSmackWheel";
	this.wheelMessages = "";
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate(["<div id=\"wheelHeader\" class=\"wheel\"><ul id=\"smackWheelMenu\"><li><a href=\"javascript:toggleClass('wheelHeader','wheel');toggleClass('deal','wheel');\" title=\"Smackwheel\" id=\"wheelMenu\" class=\"highlighted\"></a></li><li><a href=\"javascript:toggleClass('wheelHeader','odds');toggleClass('deal','odds');\" title=\"Prizes and Odds\" id=\"oddsMenu\"></a></li><li><a href=\"javascript:toggleClass('wheelHeader','play');toggleClass('deal','play');\" title=\"How To Play\" id=\"playMenu\"></a></li></ul></div><div id=\"deal\" class=\"wheel\"><div id=\"wheelOdds\">Odds</div><div id=\"wheelPlay\"><h2>How To Play</h2><h3>SmackWheel</h3><p>Where the thrill of a game show meets the Internet, the SmackWheel is the Internet's first spinning wheel of goodies that is viewed by a live online audience.</p><h3>Best Guru Guesser Gets to Spin</h3><p>The person who made the best guess on the previous Smack deal (closest to without going over) gets to stop the Wheel and win a prize.</p><h3>Don't Guess and Leave</h3><p>If you win the Guru guess and don't stop the Wheel, you'll bust (aka Moose) and lose out on your chance to win a prize.</p><h3>Guru Points</h3><p>Guru points are awarded to the top 10 guessers on each deal-9 points to the best guesser and 3 points each for guessers 2-10. Guru points not only give you extra \"street cred\" with the Smack, they also give you a chance to win a prize in our monthly guru points race.</p><h3>Past Winners</h3><p>Past Wheel winners and prizes are listed under the <a href=\"/smacktv/archive\">Past Deals</a> tab.</p></div><div id=\"","__wheelType","\">","__stopWheelLink","<div id=\"v2WheelContainer\"></div><div id=\"spinnerInfo\"><img src=\"", "__avatarUri", "\" alt=\"","__winnerNickAlt","\"/><div class=\"name\"><a href=\"/shoppers/","__winnerNickLink","\" target=\"_blank\">","__winnerNick","</a>","__spinnerCity", ", ", "__spinnerState","<br /><br />member since<br />", "__winnerMemberSince", "</div><div class=\"clearFloat\"> </div></div><div id=\"wheelInfoDiv\"><table cellpadding=\"0\" cellspacing=\"0\" id=\"wheelInfoTable\"><tr class=\"highlight\"><td>Guru Points:</td><td>","__guruPoints","</td></tr><tr><td>My Page Visits:</td><td>","__profileVisits","</td></tr><tr class=\"highlight\"><td>Attendance:</td><td>","__attendancePct","</td></tr><tr><td>JF Purchases:</td><td>","__jfPurchaseCount","</td></tr><tr class=\"highlight\"><td>Smack Purchases:</td><td>","__smackPurchaseCount","</td></tr><tr><td>Wheel Spins:</td><td>","__wheelSpins","</td></tr><tr class=\"highlight\"><td>Comment Count:</td><td>","__commentCount","</td></tr></table></div><img id=\"vitalsBottom\" src=\"/smack/images/smacktv/wheel/vitals_bottom.gif\" id=\"vitalsBottom\" alt=\"\" /><div id=\"wheelMessage\"><div id=\"wheelMessageHighlight\"></div></div><div id=\"muteContainer\"><a id=\"mute_sound_toggle\" class=\"","__wheelMuteClass","\" \"href=\"#\" onclick=\"javascript:window.SmackWheel.toggleMuteSound(); return false;\" title=\"Toggle Sound\"></a></div></div></div>"]);


	this.draw();
}

StoppedSmackWheel.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier) 
	{ 
		return;
	}
	else
	{
		if (window.liveObject && window.liveObject.typeIdentifier == "LiveSmackWheel") {
			window.SmackWheel.stopWheel(this.prizeWonIndex);

			if(this.segmentSponsor != null)  {
				if (this.segmentSponsor.logoUri.match(/.swf/) == null)
					$('segmentSponsorContainer').innerHTML = '<br/><a href="' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
				else
					$('segmentSponsorContainer').innerHTML = '<br/><a href="' + this.segmentSponsor.uri + '" target="_blank"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object></a>';
				$('segmentSponsorContainer').style.display = '';
			} else  {
				$('segmentSponsorContainer').style.display = 'none';
				$('segmentSponsorContainer').innerHTML = '';
			}
			//Change any other messaging
	
		if (this.iconUri != null)
		{
			$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
			$("showName").innerHTML = this.showName;
			$("showStartTime").innerHTML = this.timeSlot;
			$("showTitle").style.display = "block";
		}
		else
		{
			$("showTitle").style.display = "none";
		}

		if (this.busted) {
			this.wheelMessages = "Oh no! It's a MOOSE!&nbsp;&nbsp;";
		} else {
			this.wheelMessages = "We have a Winner!&nbsp;&nbsp;";
		}

		
  		document.getElementById("messageCenter").className = "messageStoppedSmackWheel";
		if (this.nextSegmentType == "deal")
		{
			document.getElementById("messageCenter").innerHTML = '<div class="messageText">'+ this.wheelMessages + 'Next deal starts in</div><div class="timerText" id="stopped_wheel_timer"></div>';
		}
		else if (this.nextSegmentType == "outwit")
		{
			document.getElementById("messageCenter").innerHTML = '<div class="messageText">'+ this.wheelMessages + 'Outwit starts in</div><div class="timerText" id="stopped_wheel_timer"></div>';
		}
		else
		{
			document.getElementById("messageCenter").innerHTML = '<div class="messageText">'+ this.wheelMessages + 'The show ends in</div><div class="timerText" id="stopped_wheel_timer"></div>';
		}
  		
  		window.stopped_wheel_timer = new FlashTimer('stopped_wheel_timer', secondsRemaining(this.soldOutAt, this.currentTime, this.duration));
  		window.stopped_wheel_timer.startTimer();
  		window.liveObject = this;
			return;
	}
		else {
			globalCleanUp();
			window.liveObject = this;
		}
		
		var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor != null)  {
			var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
			if (this.sponsor.type == "c")  {
				$("logosContainer").innerHTML = sponsorHTML;
			} else  {
				$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
			}
		} else  {
			$("logosContainer").innerHTML = noSponsorHTML;
		}
		
		if(this.segmentSponsor != null)  {
			if (this.segmentSponsor.logoUri.match(/.swf/) == null)
				$('segmentSponsorContainer').innerHTML = '<br/><a href="/redirect/outbound?u=' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
			else
				$('segmentSponsorContainer').innerHTML = '<br/><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object>';
			$('segmentSponsorContainer').style.display = '';
		} else  {
			$('segmentSponsorContainer').style.display = 'none';
			$('segmentSponsorContainer').innerHTML = '';
		}
		
		document.getElementById("messageCenter").className = "messageStoppedSmackWheel";
		if (this.nextSegmentType == "deal")
		{
			document.getElementById("messageCenter").innerHTML = '<div class="messageText">'+ this.wheelMessages + 'Next deal starts in</div><div class="timerText" id="stopped_wheel_timer"></div>';
		}
		else if (this.nextSegmentType == "outwit")
		{
			document.getElementById("messageCenter").innerHTML = '<div class="messageText">'+ this.wheelMessages + 'Outwit starts in</div><div class="timerText" id="stopped_wheel_timer"></div>';
		}
		else
		{
			document.getElementById("messageCenter").innerHTML = '<div class="messageText">'+ this.wheelMessages + 'The show ends in</div><div class="timerText" id="stopped_wheel_timer"></div>';
		}
		window.stopped_wheel_timer = new FlashTimer('stopped_wheel_timer', secondsRemaining(this.soldOutAt, this.currentTime, this.duration));
		window.stopped_wheel_timer.startTimer();
		window.liveObject = this;
	}
	
	if (!window.mute)
		this.template.update("wheelMuteClass", "wheelMute");
	else
		this.template.update("wheelMuteClass", "wheelUnMute");
	
	if (this.contestant_token)
		this.template.update("wheelType", "wheelContestant");
	else
		this.template.update("wheelType", "wheelAudience");
		
	if (this.contestant)
	{
		if (this.contestant.city != "null")
		{
			this.template.update("spinnerCity", this.contestant.city);
			this.template.update("spinnerState", this.contestant.state);
		}
		else
		{
			this.template.update("spinnerCity", "Nowheresville");
			this.template.update("spinnerState", "NP");
		}
		this.template.update("wheelSpins", this.contestant.spinCount);		
		this.template.update("winnerNickAlt",  this.contestant.nickname);
		this.template.update("winnerNickLink",  this.contestant.shopperPageName);
		this.template.update("winnerMemberSince", this.contestant.memberSinceDate);
		this.template.update("winnerNick",  this.contestant.nickname);
		this.template.update("profileVisits",  this.contestant.profileVisits);
		this.template.update("attendancePct",  this.contestant.attendancePct);
		this.template.update("jfPurchaseCount",  this.contestant.jfPurchaseCount);
		this.template.update("smackPurchaseCount",  this.contestant.smackPurchaseCount);
		this.template.update("guruPoints",  this.contestant.guruPoints);
		this.template.update("commentCount",  this.contestant.commentCount);
		this.template.update("avatarUri", this.contestant.avatarUri);
		
	}
	
	if (this.contestant_token)
	{
		this.template.update("wheelType", "wheelContestant");
		this.template.update("stopWheelLink", "");
	}
	else
	{
		this.template.update("wheelType", "wheelAudience");
		this.template.update("stopWheelLink", "");
	}
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
	
	if (this.busted) {
		this.wheelMessages = "Oh no! It's a MOOSE!&nbsp;&nbsp;";
	} else {
		this.wheelMessages = "We have a Winner!&nbsp;&nbsp;";
	}
		
	window.SmackWheel = new SmackWheelV2();
	window.SmackWheel.drawWheel("v2WheelContainer", this.prizes, this.slowdown_factor);
	window.SmackWheel.startWheel();
	window.SmackWheel.stopWheel(this.prizeWonIndex);

	if( (window.SmackWheel) ) {
	  this.drawOdds();
	}

}

StoppedSmackWheel.prototype.drawOdds = function() {
  h  = "<ul id=\"wheelOddsList\">";
  for(var p=0; p < window.SmackWheel.odds.length; p++) {
    h += "<li><b>" + window.SmackWheel.odds[p].name + " (" + window.SmackWheel.odds[p].odds + "%)</b><br />" + window.SmackWheel.odds[p].description + "</li>"
  }
  h += "</ul>";
  $('wheelOdds').innerHTML = h;
}


StoppedSmackWheel.prototype.cleanUp = function()
{
	window.SmackWheel.killWheel();
	window.stopped_wheel_timer.cleanUp();
	document.getElementById("liveObjectContainer").removeAttribute("class"); 
}



http://www.jellyfish.com/smack/javascripts/chat/Chat.js

Array.prototype.include = function(value) {
  for(var c=0;c<this.length;c++) {
    if(this[c] == value) {
      return true;
    }  
  }
  return false;
}


Chat = function(json_hash, shoppersPages) {
	if (!window.chatMonitor) {
		window.chatMonitor = new Array();
		window.chatLimit = 100;
	}
	
	if (shoppersPages)
		this.shoppersPages = true;
	
	for(var i in json_hash) {
		this[i] = json_hash[i];
	}

  this.template = new HypertextTemplate(["<div class=\"commentFloatContainer\"><div class=\"","__commentClass","\"><div class=\"rightFloater\"><div class=\"iconsContainer","__extraWidth","\">","__iconString","<div class=\"clearFloat\"> </div></div><div class=\"largeBadge\">","__largeBadge","</div><div class=\"clearFloat\"> </div></div><div class=\"chatAvatarContainer\"><a href=\"/shoppers/", "__nickName4", "\" target=\"_blank\"><img src=\"","__avatarURL","\" class=\"chatAvatar\" alt=\"","__nickName1","\" /></a></div>","<div class=\"commentInfo\"><a href=\"/shoppers/","__nickName3","\" class=\"chatNick\" target=\"_blank\">","__nickName2","</a> <span class=\"chatGuru\">\(","__guruPoints","\)</span> <span class=\"chatTime\">","__timeStamp","</span> <a href=\"#\" onclick=\"shusher.shush('", "__encryptedCommenterId", "', 1, '", "__commentId1", "'); $('", "__commentId2", "_wait_image').style.display='inline';return false;\" class=\"chatMute\" id=\"", "__commentId4", "_shush\">","__muteStatus","</a> <span id=\"", "__commentId3", "_wait_image\" class=\"commentPleaseWait\" style=\"display: none;\"> Please wait...</span><div class=\"commentText\">","__commentText","</div></div><div class=\"clearFloat\"> </div></div></div>"]);
  
	if ($("loadingChat")) {
		$("chat").removeChild($("loadingChat"));
	}
	
	if ($('comment_posted_successfully')) {
	  $('comment_posted_successfully').style.display = 'none';
	}
	
	globalSetMostRecentCommentId(this.array_of_comments[0].id);
	
	this.array_of_comments.reverse();
	
  for(var x = 0; x < this.array_of_comments.length; x++) {
    if(! window.chatMonitor.include(this.array_of_comments[x].id)) {
  		 this.addComment(this.array_of_comments[x]);
       window.chatMonitor.push(this.array_of_comments[x].id);
       if (window.chatMonitor.length > window.chatLimit) {
         $("chat").removeChild($("comment" + window.chatMonitor.shift()));
       }
     }
  }
	
}

Chat.prototype.addComment = function(comment) {	
  // console.log("adding comment " + comment.id);
	var newComment = document.createElement("div");
	newComment.setAttribute("id", "comment" + comment.id);

	if((comment.author.type)&&(comment.author.type.match(/administrator/))) {
	  this.template.update("commentClass","chatPost administrator");
  } else if((comment.author.type)&&(comment.author.type.match(/moderator/))) { 
	  this.template.update("commentClass","chatPost " + comment.author.type);
  } else {
    
    	if (comment.author.muted) {
    		this.template.update("commentClass", "chatPostMuted");
    	}	else {
    		this.template.update("commentClass", "chatPost");
    	}     
	
  }
    
	  
	  
	this.template.update("commentID", comment.id);
	
	if (comment.author.avatarUri == "") {
		this.template.update("avatarURL", "/smack/images/smacktv/chat/avatar.gif");
	} else {
		this.template.update("avatarURL", comment.author.avatarUri);
	}
	
	this.template.update("nickName1", comment.author.nickname);
	this.template.update("nickName2", comment.author.nickname);
	this.template.update("nickName3", comment.author.shopperPageName);
	this.template.update("nickName4", comment.author.shopperPageName);
	this.template.update("guruPoints", comment.author.guruPoints);
	this.template.update("timeStamp", comment.timestamp);
	
	this.template.update("encryptedCommenterId", comment.author.id);
	
	this.template.update("commentId1", "comment"+comment.id);
	this.template.update("commentId2", "comment"+comment.id);
	this.template.update("commentId3", "comment"+comment.id);
	this.template.update("commentId4", "comment"+comment.id);
	
	if(comment.author.type != "administrator") {
  	if (comment.author.muted) {
  		this.template.update("muteStatus", "UnMute");
  	} else {
  		this.template.update("muteStatus", "Mute");
  	}
  }
	
	this.template.update("commentText", comment.text);

	if (comment.author.largeIcon != null)
		this.template.update("largeBadge", "<img src=\"" + comment.author.largeIcon.uri + "\" alt=\"" + comment.author.largeIcon.altText + "\" />");
	else
		this.template.update("largeBadge", "");

	icon_string = '';
	if (comment.author.smallIcons.length > 3)
	{
		this.template.update("extraWidth", " wideIcons");
	}
	else
	{
		this.template.update("extraWidth", " thinIcons");
	}
	
	for(var c=0; c < comment.author.smallIcons.length; c++) {
	  icon_string += '<img src="' + comment.author.smallIcons[c].uri + '" alt="' + comment.author.smallIcons[c].altText + '" class="smallIcon" style="border: 0px;" />';
	}
	this.template.update("iconString", icon_string);
	
	document.getElementById("chat").insertBefore(newComment, document.getElementById("chat").firstChild);
	document.getElementById("comment" + comment.id).innerHTML = this.template.renderHTML();
	
	if (this.shoppersPages)
		new Effect.Highlight($("comment" + comment.id).firstChild, { endcolor:"#ffffff", startcolor:"#d4edee" } );
	else
		new Effect.Highlight($("comment" + comment.id).firstChild, { endcolor:"#011830", startcolor:"#e0f0b3" } );
}





http://www.jellyfish.com/smack/javascripts/SmackTVController.js

SmackTVController = function(channel_id)
{
	this.interval = 10000; //10 seconds
	this.type = 1;
	this.channel_id = channel_id;
	this.segment_id = 0;
	this.segment_state = "null";
	this.guru_guessing_state = "null";
	this.most_recent_comment_id = 0;
	this.xhr = null;
	
	// Pre-Fetching Stuff
	this.preFetchTimeout = null;
	this.doPreFetch = false;
	this.nextSegment = null;
	this.imageCache = null;
	
	this.refresh();
}

SmackTVController.prototype =
{
	start: function()
	{
    	this.timer = setInterval(this.refresh.bind(this), this.interval);
  	},
	
	stop: function()
	{
		clearInterval(this.timer);
	},
  
	refresh: function()
	{
		this.setFailSafe();
		if ((this.xhr == null) || (this.xhr.transport.readyState == 4))
		{
	  		this.request();
  		}
  	},
  
	getUrl: function()
	{
       var pollerUrlParts = [
       		'/sts?type=',this.type,
       		'&channel_id=', this.channel_id,
       		'&segment_id=', this.segment_id,
       		'&segment_state=', this.segment_state,
       		'&guru_guessing_state=', this.guru_guessing_state,
       		'&most_recent_comment_id=', this.most_recent_comment_id,
       		'&r=',Math.random(9999999999999)
       	];
       	if (this.doPreFetch)  {
       	    pollerUrlParts.push('&pre_fetch=true');
       	    this.doPreFetch = false;
       	}
	    return pollerUrlParts.join('');
	},
  
	request: function()
	{
		this.xhr = new Ajax.Request(this.getUrl(), {asynchronous: true, method: "get", parameters: "", onSuccess: globalResponseHandler});
	},

	// Called by global function globalHandleResponse()
	handleResponse: function(json_text)
	{ 
    	this.clearFailSafe();
    	var x = json_text.parseJSON();
    	for(var k in x)
    	{
      		var tempStaticObject;
      		switch(k)
      		{
      		  case "js": 
      		    eval(x.js);
      		    break;
        		case "state": 
          			this.handleState(x.state);
          		break;
				case "segment": 
					for(var j in x.segment)
					{
						var tempLiveObject;
      					switch(j)
      					{
							case "Election":
								tempLiveObject = new Election(x.segment.Election);
							break;   
							case "LiveDeal":
								tempLiveObject = new LiveDeal(x.segment.LiveDeal);
							break;
							case "SoldOutDeal":
								tempLiveObject = new SoldOutDeal(x.segment.SoldOutDeal);
								this.setPreFetchInterval();
							break;
							case "LiveSmackWheel":
								tempLiveObject = new LiveSmackWheel(x.segment.LiveSmackWheel, s.segment_id);
							break;  
							case "StoppedSmackWheel":
								tempLiveObject = new StoppedSmackWheel(x.segment.StoppedSmackWheel);
							break;
							case "AdBlob":
								tempLiveObject = new AdBlob(x.segment.AdBlob);
							break;
							case "LiveOutwitRegistration":
								tempLiveObject = new LiveOutwitRegistration(x.segment.LiveOutwitRegistration);
							break;
							case "CompletedOutwitRegistration":
								tempLiveObject = new CompletedOutwitRegistration(x.segment.CompletedOutwitRegistration);
							break;
							case "PreOutwitWithoutContestant":
								tempLiveObject = new PreOutwitWithoutContestant(x.segment.PreOutwitWithoutContestant);
							break;
							case "PreOutwitWithContestant":
								tempLiveObject = new PreOutwitWithContestant(x.segment.PreOutwitWithContestant);
							break;
							case "LiveOutwit":
								tempLiveObject = new LiveOutwit(x.segment.LiveOutwit);
							break;
							case "CompletedOutwit":
								tempLiveObject = new CompletedOutwit(x.segment.CompletedOutwit, x.state.outwitJackpot, x.state.outwitBonusJackpot);
							break;
							case "ShowPreview":
								tempLiveObject = new ShowPreview(x.segment.ShowPreview);
							break;
		      			}
					}
          		break;
          		case "guruGuessing":
          			tempStaticObject = new GuruGuessing(x.guruGuessing);
          		break;
          		case "chat":
          			tempStaticObject = new Chat(x.chat);
          		break;
        		case "toJSONString":
          		break;
          		case "preFetch":
          		    window.s.nextSegment = x.preFetch;
          		    window.s.downloadImages();
          		break;
      		}
    	}
  	},

	handleState: function(state)
	{
    	this.segment_id = state.segmentId;
    	this.guru_guessing_state = state.guruGuessingState;
    	this.segment_state = state.segmentState;
    	if (window.liveObject instanceof LiveOutwitRegistration || window.liveObject instanceof CompletedOutwitRegistration ||
    	    window.liveObject instanceof LiveOutwit || window.liveObject instanceof CompletedOutwit)  {
	    	if (state.countdownDuration)
	    	{
		    	window.liveObjectTimer.syncTimer(state.countdownDuration);
		    }
		}
		if (window.sdq_points != state.sdqJackpot)
		{
			window.sdq_points = state.sdqJackpot;
			globalUpdateSDQ();
		}
		$("jackpot").innerHTML = "$" + state.outwitJackpot;
		$("bonus").innerHTML = "$" + state.outwitBonusJackpot;
	},
	
	setFailSafe: function()
	{
		this.fail_safe = setTimeout("globalFailSafe()", 60000);
	},
	
	clearFailSafe: function()
	{
		clearTimeout(this.fail_safe);
	},
  
	// Called by global function globalFailSafe() 
	doFailSafe: function()
	{
    	this.stop();
    	this.start();
	},
	// Pre-fetch stuff
	setPreFetchInterval: function()  {
	   var timeout = ((60 * Math.random()) + 10) * 1000;
	   this.preFetchTimeout = setTimeout("window.s.enablePreFetch();", timeout);
	},
	enablePreFetch: function()  {
	   this.doPreFetch = true;
	   clearTimeout(this.preFetchTimeout);
	   this.preFetchTimeout = null;
	},
	doSwitchOver: function()  {
	   if (this.nextSegment && this.nextSegment.LiveSmackWheel)  {
	       tempStaticObject = new LiveSmackWheel(this.nextSegment.LiveSmackWheel, this.nextSegment.LiveSmackWheel.segmentId);
	   }
	   this.nextSegment = null;
	},
	downloadImages: function()  {
    	this.imageCache = new Array();

    	for (var i = 0; i < this.nextSegment.LiveSmackWheel.prizes.length; i++)  {
    	   this.imageCache[i] = new Image;
    	   this.imageCache[i].src = "/smack/images/smacktv/wheel/tiles/" + this.nextSegment.LiveSmackWheel.prizes[i].imageUri;
    	}
	   
	}
}

http://www.jellyfish.com/smack/javascripts/election/Election.js

Election = function(json_hash) {
	for(var i in json_hash) {
		this[i] = json_hash[i];
	}
  this.template = new HypertextTemplate(["<tr class=\"","__electionRowType","\" id=\"row_","__toggleIdRow","\"><td><a href=\"","__productURL","\" target=\"new\">","__productName","</a></td><td><span id=\"choice_","__electionRowChoiceId1","\">","__productPercent","</span>%</td><td style=\"width:70px;\"><a href=\"#\" onclick=\"new Ajax.Request('/smacktv/voteForElection?c=", "__electionRowChoiceId", "', {asynchronous:true, evalScripts:true});window.liveObject.userVote='","__userVoteToggleID","';window.liveObject.updateImages();\"","__toggleLink"," return false;\"><img id=","__toggleId"," src=\"","__electionRowImage","\" alt=\"","__electionRowAlt","\" /></a></td></tr>"]);
  this.draw();
}
Election.inherits(Segment);

Election.prototype.draw = function() {
  if(window.liveObject instanceof Election) {
    if(this.winningVoteId) {
      this.showWinner(this.winningVoteId);
    } else {
      this.updateVoting();
      this.updateImages();
    }
  } else {
    globalCleanUp(); 
    window.liveObject = this;
    this.initialize();
  }
  
  	if (this.sponsor != null)
	{
		$("logosContainer").innerHTML = "<a href=\"" + this.sponsor.uri + "\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	}
	else
	{
		$("logosContainer").innerHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	}
  
  	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}
}

Election.prototype.initialize = function() {
  this.initializeTimer();
  this.initializeVoting();
}

Election.prototype.initializeVoting = function() {    
  var electionTable = new Array();
  electionTable.push("<div id=\"election\"><img src=\"/smack/images/smacktv/election/vote_header.gif\" alt=\"Vote for the next Smack Deal\" /><table cellpadding=\"0\" cellspacing=\"0\">");
  
  for (var i = 0; i < this.choices.length; i++) {
    this.template.update("toggleLink", "$('vote" + this.choices[i].id + "').src = '/smack/voting/jf_ss_thanks_button1.gif';");
  	this.template.update("toggleId", "vote" + this.choices[i].id);
  	this.template.update("toggleIdRow", this.choices[i].id);
  	this.template.update("userVoteToggleID", this.choices[i].id);
    this.template.update("electionRowType", "electionProduct");
    this.template.update("electionRowChoiceId", this.choices[i].id);
    this.template.update("electionRowChoiceId1", this.choices[i].id); //
    this.template.update("productURL", "/products/offerings/" + this.choices[i].product.categoryId + "/" + this.choices[i].product.id);
    this.template.update("productName", this.choices[i].product.name);
    this.template.update("productPercent", this.choices[i].votePct.toFixed(2));
    
    if (this.userVote == this.choices[i].id && this.votingOpen)
    {
    	this.template.update("electionRowImage", "/smack/voting/jf_ss_thanks_button1.gif");
    	this.template.update("electionRowAlt", "Thanks");
    }
    else if (this.userVote == null && this.votingOpen)
    {
    	this.template.update("electionRowImage", "/smack/jf_ss_vote_button.gif");
    	this.template.update("electionRowAlt", "Vote");
    }
    else if (!this.votingOpen && this.choices[i].id == this.winningVoteId)
    {
    	this.template.update("electionRowImage", "/smack/images/jf_ss_winner_button.gif");
    	this.template.update("electionRowAlt", "Winner");
    	this.template.update("electionRowType", "electionWinner");
    }
    else
    {
    	this.template.update("electionRowImage", "/smack/images/smacktv/trans.gif");
    	this.template.update("electionRowAlt", "Voting Closed");
    }
    
    electionTable.push(this.template.renderHTML());
    electionTable.push("<tr><td colspan=\"3\"><img src=\"/smack/images/smacktv/trans.gif\" style=\"height:7px;\" alt=\"\" /></td></tr>");
  
  }
  electionTable.push("</table>");
  electionTable.push('<div id="suggestions" style="text-align: right; padding: 0px 30px 5px 0px;"><a href="#"onclick="Election.prototype.toggleSuggestionBox(); return false;">Send a Product Suggestion</a></div>'
            + '<div id="ideas_for_smackdaddy" style="display: none; padding: 0px 10px 0px 15px;"><h2 style="font-size: 20px;">Ideas for SmackDaddy</h2><p>Is there something special you\'d like to see SmackDaddy offer up for Deal of the Day? Send your product suggestion now!</p>'
            + '<p><label for="suggestion_text">Your suggestion</label> <input type="text" id="suggestion" name="suggestion" id="suggestion_text" /></p>'
            + '<p style="text-align: center; padding-top: 3px;"><input type="image" src="/smack/send.gif" id="tell_smackdaddy_button" onclick="Election.prototype.doIdeaRequest(); this.onclick=function(){return false;}" value="Tell SmackDaddy" /> <a href="#" style="font-size: 0.9em; color: #021931;" onclick="Effect.BlindUp(\'ideas_for_smackdaddy\');return false;">cancel</a></p>'
            + '<p id="idea_message" style="text-align: center; margin: 15px 0px; display: none;">Thanks for your suggestion!</p>'
            + '</div>'
  );
  electionTable.push("<img src=\"/smack/images/smacktv/election/vote_footer.gif\" alt=\"Winner kicks off the next show\" /></div>");
  document.getElementById("liveObjectContainer").innerHTML = electionTable.join("");
}

Election.prototype.initializeTimer = function() {
  document.getElementById("messageCenter").className = "messageElection";
  document.getElementById("messageCenter").innerHTML = '<div class="messageText">The next Smack Show starts in</div><div class="timerText" id="election_timer"></div>';
  window.election_timer = new FlashTimer('election_timer',this.duration);
  window.election_timer.startTimer();
}

Election.prototype.updateVoting = function() {
  for (var i = 0; i < this.choices.length; i++) {
    $('choice_'+this.choices[i].id).innerHTML = this.choices[i].votePct.toFixed(2);
    // console.log('Updating choice_' + this.choices[i].id + ' to ' + this.choices[i].votePct.toFixed(2));
  }
}

Election.prototype.updateImages = function() {
  for (var i = 0; i < this.choices.length; i++) {
	
	if (this.userVote == this.choices[i].id && this.votingOpen)
    {
    	$("vote" + this.choices[i].id).src = "/smack/voting/jf_ss_thanks_button1.gif"
    	$("row_" + this.choices[i].id).className = "electionProductClosed";
    	$("vote" + this.choices[i].id).setAttribute("alt", "Thanks");
    }
    else if (this.userVote == null && this.votingOpen)
    {
    	// $("vote" + this.choices[i].id).src = "/smack/images/smacktv/election/vote.gif";
    	$("vote" + this.choices[i].id).src = "/smack/jf_ss_vote_button.gif";
    	$("row_" + this.choices[i].id).className = "electionProductClosed";
    	$("vote" + this.choices[i].id).setAttribute("alt", "Vote");
    }
    else if (!this.votingOpen && this.choices[i].id == this.winnerId)
    {
      $("row_" + this.choices[i].id).getElementsByTagName('a')[1].onclick = function(){ return false; }
    	$("vote" + this.choices[i].id).src = "/smack/images/jf_ss_winner_button.gif"
    	$("row_" + this.choices[i].id).className = "electionWinner";
    	$("vote" + this.choices[i].id).setAttribute("alt", "Winner");
    }
    else
    {
    	$("vote" + this.choices[i].id).src = "/smack/images/smacktv/election/trans.gif"
    	$("row_" + this.choices[i].id).className = "electionProductClosed";
    	$("vote" + this.choices[i].id).setAttribute("alt", "Voting Closed");
    }
  }
}

Election.prototype.showWinner = function(winnerId) {
  // console.log("Showing winner " + winnerId);
  for (var i = 0; i < this.choices.length; i++) {
  	$("vote" + this.choices[i].id).src = "/smack/images/smacktv/election/trans.gif"
  	$("row_" + this.choices[i].id).className = "electionProductClosed";
  	$("vote" + this.choices[i].id).setAttribute("alt", "Voting Closed");
  }
  $("row_" + winnerId).getElementsByTagName('a')[1].onclick = function(){ return false; }
  $("vote" + winnerId).src = "/smack/images/jf_ss_winner_button.gif"
  $("row_" + winnerId).className = "electionWinner";
  $("vote" + winnerId).setAttribute("alt", "Winner");
}

Election.prototype.cleanUp = function() {
  window.election_timer.cleanUp();
}

Election.prototype.toggleSuggestionBox = function()  {
    if ($('ideas_for_smackdaddy').style.display == 'none')
        Effect.BlindDown('ideas_for_smackdaddy');
    else
        Effect.BlindUp('ideas_for_smackdaddy');
}

Election.prototype.doIdeaRequest = function()  {
    new Ajax.Request('/smacktv/suggestion', {
        asynchronous: true,
        method: "post",
        parameters: "suggestion="+$F('suggestion'),
        onSuccess: Election.prototype.doIdeaResponse }
    );
    return false;
}

Election.prototype.doIdeaResponse = function()  {
    $('idea_message').style.display = '';
    setTimeout("Effect.BlindUp('ideas_for_smackdaddy')", 1000);
    setTimeout("$('suggestion').value = '';$('idea_message').style.display = 'none';", 2000);
    setTimeout("$('tell_smackdaddy_button').onclick = function() {Election.prototype.doIdeaRequest(); this.onclick=function(){return false;}}", 2000);
}

http://www.jellyfish.com/smack/javascripts/guru_guessing/GuruGuessing.js

var g = null;
GuruGuessing = function(json_hash) {
	for(var i in json_hash)	{
		this[i] = json_hash[i];
	}
	this.template;
	this.draw();
	g = this;
}

GuruGuessing.prototype.draw = function() {

	if (this.state == "MakeGuess") {		
		this.template = new HypertextTemplate(["<div id=\"guruError\" style=\"display: none;\"></div><div id=\"guruMakeGuess\"><h2>Guess the Best Deal&mdash;Spin the Wheel!</h2><div id=\"guruHasNick\"><form action=\"/smacktv/makeGuess\" onsubmit=\"new Ajax.Request('/smacktv/makeGuess', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\"><input type=\"text\" name=\"user_guess\" /> <span id=\"guruTip\">Your Guess (e.g. 14.45%)</span><input type=\"image\" style=\"display:block;margin:5px 0px 10px 0px;height:15px;width:152px;\" src=\"/smack/images/smacktv/guru/make_your_guess.gif\" onclick=\"$('guru_guess_wait').style.display='inline';\" /><img src=\"/smack/jf_smack_spinner.gif\" alt=\"Please wait\" style=\"display: none;\" id=\"guru_guess_wait\" /><input type=\"hidden\" name=\"encrypted_u_id\" value=\"" + window.eu + "\" /><input type=\"hidden\" name=\"smack_of_the_day\" value=\"" + window.liveObject.id + "\" /></form></div><div id=\"guruNoNick\"></div>Guessing closes in <span id=\"guruTimer\"></span></div>"]);	
		if (window.nickname != null) {
			document.getElementById("guru").innerHTML = this.template.renderHTML();
		}	else {
			document.getElementById("guru").innerHTML = "You must enter an nickname in order to participate in Guru Guessing";
		}
	    window.guru_timer = new FlashTimer('guruTimer', this.duration, { endText: "Guessing is closed" });
    	window.guru_timer.startTimer(); 
	}
	
	if (this.state == "StayTuned") {	
		this.template = new HypertextTemplate(["<div id=\"guruError\" style=\"display: none;\"></div><div id=\"guruStayTuned\"><img src=\"/smack/images/smacktv/guru/stay_tuned.gif\" alt=\"Stay Tuned\" />Smack Guru Guessing will open at the start of the next deal.</div>"]);
		document.getElementById("guru").innerHTML = this.template.renderHTML(); 
		this.stopGuruTimer();
	}
	
	if (this.state == "NoGuessClosed") {
		this.template = new HypertextTemplate(["<div id\"guruError\" style=\"display: none;\"></div><div id=\"guruGuessingClosed\"><img src=\"/smack/images/smacktv/guru/guessing_is_closed.gif\" alt=\"Guessing is Closed\" />You'll have to be quicker next time.</div>"]);
		document.getElementById("guru").innerHTML = this.template.renderHTML(); 
		this.stopGuruTimer();
	}
	
	if (this.state == "GuessClosed") {	
		this.template = new HypertextTemplate(["<div id=\"guruError\" style=\"display: none;\"></div><div id=\"guruPillLeft\">Your Guess<div id=\"guruYourGuess\">","__yourGuess","%</div></div><div id=\"guruPillRight\">Over Guessers<div id=\"guruOverGuessers\">","__overGuessers","</div></div><div class=\"clearFloat\"> </div>"]);
		this.template.update("yourGuess", this.your_guess.toFixed(2));
		this.template.update("overGuessers", this.overGuessers.toFixed(2) + "%");
		document.getElementById("guruIndicator").style.top = this.your_guess + "%";
		document.getElementById("guruIndicator").style.display = "block";		
		document.getElementById("guru").innerHTML = this.template.renderHTML(); 
		this.stopGuruTimer();
	}
	
	if (this.state == "NoGuessing")  {
		$('guruContainer').style.display = "none";
	} else if (this.state != null)  {
		$('guruContainer').style.display = "block";
	}
	
if (this.state == "GuruWinners")
{
	this.template = new HypertextTemplate(["<div id=\"guruError\" style=\"display: none;\"></div><div id=\"guruWinnerContainer\"><div id=\"guruGuessed\">Your Guess<div id=\"guruYourGuess\">","__yourGuess","%</div></div><div class=\"clearFloat\"> </div><div id=\"guruWinners\"><img src=\"/smack/images/smacktv/guru/the_winners.gif\" alt=\"Top Guesses\" /><div id=\"guruWinnersTable\"></div></div></div><div id=\"guruBestGuess\" style=\"","__bestGuessStyle","\"><img src=\"/smack/images/smacktv/guru/best_guess_top.gif\" alt=\"Best Guess\" /><div><img id=\"bestGuessAvatar\" src=\"","__bestAvatar","\" alt=\"","__bestNickName1","\" /><br />","__bestNickName2","<span>","__bestGuess","%</span></div></div><div class=\"clearFloat\"> </div>"]);
	
	if (this.yourGuess)
	{
		this.template.update("yourGuess", this.yourGuess.toFixed(2));
	}

	if (this.winners.length != 0)
	{
		if (this.winners[0].avatarUri != null)
		{
			this.template.update("bestAvatar", this.winners[0].avatarUri);
		}
		else
		{
			this.template.update("bestAvatar", "/smack/images/smacktv/chat/avatar.gif");
		}

		this.template.update("bestNickName1", this.winners[0].nickname);
		this.template.update("bestNickName2", this.winners[0].nickname);
		this.template.update("bestGuess", this.winners[0].guess.toFixed(2));

		this.template.update("bestGuessStyle", "display:block;");
	}
	else
	{
		this.template.update("bestGuessStyle", "display:none;");
	}
	
	document.getElementById("guru").innerHTML = this.template.renderHTML();
	
	if (!this.yourGuess)
	{
		document.getElementById("guruGuessed").style.display = "none";
		document.getElementById("guruWinners").style.marginTop = "0px";
	}
		
	if (this.winners.length != 0)
	{
		var winnerTable = new Array();
		winnerTable.push("<div><table id=\"tableOfGuruGuesses\" cellpadding=\"0\" cellspacing=\"0\"><tr class=\"header\"><td>Rank</td><td>Nickname</td><td>Points</td><td>Guess</td></tr>");

		for(var i = 0; i < this.winners.length; i++)
		{
			if ( i % 2 != 0)
			{
				tableHighlight = "";
			}
			else
			{
				tableHighlight = " class=\"highlight\"";
			}
			winnerTable.push("<tr" + tableHighlight + "><td class=\"rank\">" + (i+1) + "</td><td><a target=\"_blank\" href=\"/shoppers/" + this.winners[i].shopperPageName + "\">" + this.winners[i].nickname + "</a></td><td>" + this.winners[i].points + "</td><td class=\"guess\">" + this.winners[i].guess.toFixed(2) + "%</td></tr>");
		}
		
		winnerTable.push("</table></div>");
		document.getElementById("guruWinnersTable").innerHTML = winnerTable.join("");
	}
	else
	{
		document.getElementById("guruWinnersTable").innerHTML = "<div><table id=\"tableOfGuruGuesses\" cellpadding=\"0\" cellspacing=\"0\"><tr class=\"header\"><td>Rank</td><td>Nickname</td><td>Points</td><td>Guess</td></tr><tr class=\"highlight\"><td colspan=\"4\">Oops, no one guessed correctly.</td></tr></table></div>";
	}
	
	this.stopGuruTimer();
	return;
}

}


GuruGuessing.prototype.stopGuruTimer = function() {
  if(window.guru_timer) {
    window.guru_timer.cleanUp();
  }
}

http://www.jellyfish.com/smack/javascripts/outwit/Outwit.js

Outwit = function(json_hash)
{	
	this.typeIdentifier = "Outwit";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate([
		"<div id=\"deal\" class=\"outwit\">",
			"<div id=\"outwitCoins\">WIN<div id=\"outwitPot\">$","__outwitPot","</div></div>",
			"<img src=\"outwit_title.gif\" alt=\"Outwit the Smack\" />",
		"</div>"
	]);

 	this.draw();
}

Outwit.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
		return;
	else
	{
		globalCleanUp();
		window.liveObject = this;
	}
	
	this.template.update("outwitPot", "2300");
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
}

Outwit.prototype.cleanUp = function()
{

}

http://www.jellyfish.com/smack/javascripts/outwit/LiveOutwit.js

LiveOutwit = function(json_hash)
{	
	this.typeIdentifier = "LiveOutwit";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate([
		"<div id=\"outwitHeader\" class=\"outwit\">",
			"<ul id=\"outwitMenuList\">",
				"<li><a href=\"javascript:toggleClass('outwitHeader','outwit');toggleClass('deal','outwit');\" title=\"Outwit the Smack\" id=\"outwitMenu\" class=\"highlighted\"></a></li>",
				"<li><a href=\"javascript:toggleClass('outwitHeader','outwitRules');toggleClass('deal','outwitRules');\" title=\"Rules and FAQs\" id=\"outwitRulesMenu\"></a></li>",
			"</ul>",
		"</div>",
		"<div id=\"deal\" class=\"outwit\">",
			"<div id=\"outwitContainer\">",
				"<div id=\"outwitCoins\">WIN<div id=\"outwitPot\">$","__outwitPot","</div></div>",
				"<img src=\"/smack/images/smacktv/outwit/outwit_title.gif\" alt=\"Outwit the Smack\" />",
				"<div class=\"clearFloat\"> </div><br /><br />",
				"__outwitContent",
			"</div>",
			"<div id=\"outwitRulesContainer\">",
"<h3>Rules &amp; How To Play</h3><p>Think you can outwit the Smack?  Now's your chance...In between certain Smack deals, we will start playing the Outwit the Smack game.</p><h3>Random Contestant</h3><p>The game will start when Smack Daddy selects a random person from the Smack show audience.  (Actually, a computer generated process will randomly select a shopper from a list of smack show participants that respond to the opt-in message at the start of the game). One lucky contestant will then \"come on down\" for their turn on the Smack stage.</p><h3>One Question, Everyone Plays</h3><p>Both the contestant and the rest of the smack audience will be presented with the same question with multiple choice answers. Everyone will then have a short time to put in a blind answer to the question, trying to \"outwit\" the rest of the smack community by selecting the <b>LEAST POPULAR</b> answer. If you select the least popular answer, you win, whether you are the contestant or in the studio audience.</p><h3>What Do I Win?</h3><p>Winning contestants will receive 3 guru points and a cash prize identified at the start of the game. Winning audience members will receive 1 guru point to build towards the monthly guru points race. The cash prize will be a progressive pot: if an Outwit contestant loses, we will add to the cash amount for the next game (typically in increments of $10).</p><h3>What About Ties?</h3><p>Ties will still win.  That's just the way Smack Daddy rolls.  If we receive an exact number of responses to the same answer, either answer will count towards a win.</p><p><a href=\"/smacktv/aboutOutwit\">Now a Word from Carl's Lawyers &mdash; Official Rules</a></p>",
			"</div>",
		"</div>"
	]);

	this.alreadyClicked = false;
 	this.draw();
}

LiveOutwit.prototype.draw = function()
{

	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
		return;
	else
	{
		globalCleanUp();
		window.liveObject = this;
		this.initializeTimer();
	}
	
	var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	if (this.sponsor != null)  {
		var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor.type == "c")  {
			$("logosContainer").innerHTML = sponsorHTML;
		} else  {
			$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
		}
	} else  {
		$("logosContainer").innerHTML = noSponsorHTML;
	}
	
	if(this.segmentSponsor != null)  {
		if (this.segmentSponsor.logoUri.match(/.swf/) == null)
			$('segmentSponsorContainer').innerHTML = '<br/><a href="/redirect/outbound?u=' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
		else
			$('segmentSponsorContainer').innerHTML = '<br/><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object>';
		$('segmentSponsorContainer').style.display = '';
	} else  {
		$('segmentSponsorContainer').style.display = 'none';
		$('segmentSponsorContainer').innerHTML = '';
	}
	
	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}
	
	document.getElementById("messageCenter").className = "messageLiveDeal";
	
	
	var tempOutwitContent = "";
	
	tempOutwitContent += "<div id=\"outwitAvatar\">";
	tempOutwitContent += "<a href=\"/shoppers/" + this.contestant.shopperPageName + "\"><img src=\"" + this.contestant.avatarUri + "\" alt=\"" + this.contestant.nickname + "\" /></a>";
	tempOutwitContent += "<div><a href=\"/shoppers/" + this.contestant.shopperPageName + "\">" + this.contestant.nickname + "</a>";
	tempOutwitContent += "<br />member since<br />";
	tempOutwitContent += this.contestant.memberSinceDate;
	tempOutwitContent += "</div></div>";
	
	
	if (this.contestant.iconUris.length > 0)
	{
		var tempIcons = "";
		for(var z = 0; z < this.contestant.iconUris.length; z++)
		{
			tempIcons += "<img src=\"" + this.contestant.iconUris[z] + "\" />";
		}
	}
	else
	{
		var tempIcons = "None";
	}
	
	tempOutwitContent += "<div id=\"outwitVitals\">";
	tempOutwitContent += "<img src=\"/smack/images/smacktv/outwit/vitals_top.gif\" alt=\"Vitals\" />";
	tempOutwitContent += "<div id=\"vitalsTableContainer\">";
	tempOutwitContent += "<table cellpadding=\"0\" cellspacing=\"0\">";
	tempOutwitContent += "<tr class=\"highlighted\"><td>Guru Points: </td><td>" + this.contestant.guruPoints + "</td></tr>";
	tempOutwitContent += "<tr><td>Icons: </td><td>" + tempIcons + "</td></tr>";
	tempOutwitContent += "<tr class=\"highlighted\"><td>JF Purchases: </td><td>" + this.contestant.jfPurchaseCount + "</td></tr>";
	tempOutwitContent += "<tr><td>Smack Purchases: </td><td>" + this.contestant.smackPurchaseCount + "</td></tr>";
	tempOutwitContent += "</table>";
	tempOutwitContent += "</div>";
	tempOutwitContent += "<img src=\"/smack/images/smacktv/outwit/vitals_bottom.gif\" alt=\"Vitals\" />";
	tempOutwitContent += "</div>";
	
	
	tempOutwitContent += "<div class=\"clearFloat\"> </div><hr /><h2>" + this.question + "</h2><div id=\"outwitError\"></div>";
	for (var i = 0; i < this.answers.length; i++)
	{
		if (this.userIsIn && this.userChoice != null)
		{
			if (this.userChoice == this.answers[i].id)
				tempOutwitContent += "<a href=\"#\" class=\"outwitAnswerChecked\" onclick=\"return false;\">" + this.answers[i].text + "</a>";
			else
				tempOutwitContent += "<a href=\"#\" class=\"outwitAnswer\" onclick=\"return false;\">" + this.answers[i].text + "</a>";
		}
		else if (this.userIsIn)
		{
			tempOutwitContent += "<a href=\"#\" name=\"outwitAnswer\" id=\"outwitAnswer\" class=\"outwitAnswer\" onclick=\"if (!window.liveObject.alreadyClicked){";
			tempOutwitContent += "new Ajax.Request('/smacktv/vote_for_outwit?answer_id=";
			tempOutwitContent += this.answers[i].id;
			tempOutwitContent += "&encrypted_u_id=";
			tempOutwitContent += window.eu;
			tempOutwitContent += "&outwit_id=";
			tempOutwitContent += this.id;
			tempOutwitContent += "', {asynchronous:true, evalScripts:true, onComplete: window.liveObject.answerResponse }); $('spinner_";
			tempOutwitContent += i;
			tempOutwitContent += "').style.display = '';";
			tempOutwitContent += "window.liveObject.alreadyClicked = true;} return false;\"";
			tempOutwitContent += ">";
			tempOutwitContent += this.answers[i].text;
			tempOutwitContent += "<img src=\"/smack/jf_smack_spinner.gif\" id=\"spinner_";
			tempOutwitContent += i;
			tempOutwitContent += "\"  style=\"margin-left: 10px; display: none\" /></a>";
		}
		else
		{
			tempOutwitContent += "<a href=\"#\" class=\"outwitAnswer\" onclick=\"return false;\">" + this.answers[i].text + "</a>";
		}
	}
	
	if (this.userIsIn && this.contestantToken)
		tempOutwitContent += "<h3>Select the least popular option and you will win the jackpot.</h3>";
	else if (this.userIsIn)
		tempOutwitContent += "<h3>Select the least popular option and you will win 1 guru point.</h3>";
	else
		tempOutwitContent += "<h3>Sorry, you cannot vote because you did not opt in for this outwit.</h3>";
	
	this.template.update("outwitContent", tempOutwitContent);
	this.template.update("outwitPot", this.outwitPot);
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
}

LiveOutwit.prototype.cleanUp = function()
{
	window.liveObjectTimer.cleanUp();
}

LiveOutwit.prototype.initializeTimer = function()
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">Time Left To Make Your Choice:</div><div class="timerText" id="liveObjectTimer"></div>';
	
	window.liveObjectTimer.syncTimer(secondsRemaining(this.startedAt, this.currentTime, this.duration));
}

LiveOutwit.prototype.answerResponse = function(response)
{
    if (window.liveObject instanceof LiveOutwit)  {
        var responseObj = eval('(' + response.responseText + ')');
        if (responseObj.success)  {
        	for (var i = 0; i < window.liveObject.answers.length; i++)  {
        		if (window.liveObject.answers[i].id == responseObj.answer_id)  {
        			document.getElementsByName('outwitAnswer')[i].className = 'outwitAnswerChecked';
        			$('spinner_'+i).style.display = 'none';
        		}
        	}
        } else  {
        	$('outwitError').innerHTML = responseObj.msg + '<br/><br/>';
        	$('outwitError').style.display = 'block';
        	for (var i = 0; i < window.liveObject.answers.length; i++)
        		$('spinner_'+i).style.display = 'none';
        }
    }
}

http://www.jellyfish.com/smack/javascripts/outwit/CompletedOutwit.js

CompletedOutwit = function(json_hash, nextOutwitPot, bonusPot)
{	
	this.typeIdentifier = "CompletedOutwit";
	this.nextOutwitPot = nextOutwitPot;
	this.bonusPot = bonusPot;
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate([
		"<div id=\"outwitHeader\" class=\"outwit\">",
			"<ul id=\"outwitMenuList\">",
				"<li><a href=\"javascript:toggleClass('outwitHeader','outwit');toggleClass('deal','outwit');\" title=\"Outwit the Smack\" id=\"outwitMenu\" class=\"highlighted\"></a></li>",
				"<li><a href=\"javascript:toggleClass('outwitHeader','outwitRules');toggleClass('deal','outwitRules');\" title=\"Rules and FAQs\" id=\"outwitRulesMenu\"></a></li>",
			"</ul>",
		"</div>",
		"<div id=\"deal\" class=\"outwit\">",
			"<div id=\"outwitContainer\">",
				"<div id=\"outwitCoins\">WIN<div id=\"outwitPot\">$","__outwitPot","</div></div>",
				"<img src=\"/smack/images/smacktv/outwit/outwit_title.gif\" alt=\"Outwit the Smack\" />",
				"<div class=\"clearFloat\"> </div><br /><br />",
				"__outwitContent",
			"</div>",
			"<div id=\"outwitRulesContainer\">",
"<h3>Rules &amp; How To Play</h3><p>Think you can outwit the Smack?  Now's your chance...In between certain Smack deals, we will start playing the Outwit the Smack game.</p><h3>Random Contestant</h3><p>The game will start when Smack Daddy selects a random person from the Smack show audience.  (Actually, a computer generated process will randomly select a shopper from a list of smack show participants that respond to the opt-in message at the start of the game). One lucky contestant will then \"come on down\" for their turn on the Smack stage.</p><h3>One Question, Everyone Plays</h3><p>Both the contestant and the rest of the smack audience will be presented with the same question with multiple choice answers. Everyone will then have a short time to put in a blind answer to the question, trying to \"outwit\" the rest of the smack community by selecting the <b>LEAST POPULAR</b> answer. If you select the least popular answer, you win, whether you are the contestant or in the studio audience.</p><h3>What Do I Win?</h3><p>Winning contestants will receive 3 guru points and a cash prize identified at the start of the game. Winning audience members will receive 1 guru point to build towards the monthly guru points race. The cash prize will be a progressive pot: if an Outwit contestant loses, we will add to the cash amount for the next game (typically in increments of $10).</p><h3>What About Ties?</h3><p>Ties will still win.  That's just the way Smack Daddy rolls.  If we receive an exact number of responses to the same answer, either answer will count towards a win.</p><p><a href=\"/smacktv/aboutOutwit\">Now a Word from Carl's Lawyers &mdash; Official Rules</a></p>",
			"</div>",
		"</div>"
	]);

 	this.draw();
}

CompletedOutwit.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
		return;
	else
	{
		globalCleanUp();
		window.liveObject = this;
		this.initializeTimer();
	}
	
	var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	if (this.sponsor != null)  {
		var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor.type == "c")  {
			$("logosContainer").innerHTML = sponsorHTML;
		} else  {
			$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
		}
	} else  {
		$("logosContainer").innerHTML = noSponsorHTML;
	}
	
	if(this.segmentSponsor != null)  {
		if (this.segmentSponsor.logoUri.match(/.swf/) == null)
			$('segmentSponsorContainer').innerHTML = '<br/><a href="/redirect/outbound?u=' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
		else
			$('segmentSponsorContainer').innerHTML = '<br/><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object>';
		$('segmentSponsorContainer').style.display = '';
	} else  {
		$('segmentSponsorContainer').style.display = 'none';
		$('segmentSponsorContainer').innerHTML = '';
	}
	
	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}
	
	document.getElementById("messageCenter").className = "messageLiveDeal";
	var tempOutwitContent = "";
	
	var contestantWon = false;
	for (var i = 0; i < this.winningAnswerIds.length; i++)  {
		if(this.contestantAnswerId == this.winningAnswerIds[i])
			contestantWon = true;
	}
	if(contestantWon)
	{
		tempOutwitContent += "<div class=\"contestantWinnerBlock\">";
		
		tempOutwitContent += "<a href=\"/shoppers/";
		tempOutwitContent += this.contestant.shopperPageName;
		tempOutwitContent += "\" target=\"_blank\"><img src=\"";
		tempOutwitContent += this.contestant.smallAvatarUri;
		tempOutwitContent += "\" alt=\"";
		tempOutwitContent += this.contestant.nickname;
		tempOutwitContent += "\" /></a> <a href=\"/shoppers/";
		tempOutwitContent += this.contestant.shopperPageName;
		tempOutwitContent += "\" target=\"_blank\">";
		tempOutwitContent += this.contestant.nickname;
		tempOutwitContent += "</a>";
		
		tempOutwitContent += "<div id=\"winnerAmount\">$" + this.amountWon + "</div>";
		
		tempOutwitContent += "</div>";
	}
	else
	{
		tempOutwitContent += "<div class=\"contestantLoserBlock\">";
		
		tempOutwitContent += "<a href=\"/shoppers/";
		tempOutwitContent += this.contestant.shopperPageName;
		tempOutwitContent += "\" target=\"_blank\"><img src=\"";
		tempOutwitContent += this.contestant.smallAvatarUri;
		tempOutwitContent += "\" alt=\"";
		tempOutwitContent += this.contestant.nickname;
		tempOutwitContent += "\" /></a> <a href=\"/shoppers/";
		tempOutwitContent += this.contestant.shopperPageName;
		tempOutwitContent += "\" target=\"_blank\">";
		tempOutwitContent += this.contestant.nickname;
		tempOutwitContent += "</a>";
		
		tempOutwitContent += "</div>";
	}
	
	if (!this.contestantToken)
	{
		var userWon = false;
		for (var i = 0; i < this.guruWinnerAnswerIds.length; i++)  {
			if(this.userChoice == this.guruWinnerAnswerIds[i])
				userWon = true;
		}
		if(userWon)
		{
			tempOutwitContent += "<div class=\"guruWinnerBlock\">";
			
			tempOutwitContent += "<a href=\"/shoppers/";
			tempOutwitContent += window.nickname;
			tempOutwitContent += "\" target=\"_blank\"><img src=\"";
			tempOutwitContent += window.smallAvatarUri;
			tempOutwitContent += "\" alt=\"";
			tempOutwitContent += window.nickname;
			tempOutwitContent += "\" /></a> <a href=\"/shoppers/";
			tempOutwitContent += window.nickname;
			tempOutwitContent += "\" target=\"_blank\">";
			tempOutwitContent += window.nickname;
			tempOutwitContent += "</a>";
			
			tempOutwitContent += "</div>";
		}
		else
		{
			tempOutwitContent += "<div class=\"guruLoserBlock\">";
			
			tempOutwitContent += "<a href=\"/shoppers/";
			tempOutwitContent += window.nickname;
			tempOutwitContent += "\" target=\"_blank\"><img src=\"";
			tempOutwitContent += window.smallAvatarUri;
			tempOutwitContent += "\" alt=\"";
			tempOutwitContent += window.nickname;
			tempOutwitContent += "\" /></a> <a href=\"/shoppers/";
			tempOutwitContent += window.nickname;
			tempOutwitContent += "\" target=\"_blank\">";
			tempOutwitContent += window.nickname;
			tempOutwitContent += "</a>";
			
			tempOutwitContent += "</div>";
		}
	}
	
	tempOutwitContent += "<div class=\"clearFloat\"> </div>";

	tempOutwitContent += "<h4>Next Pot: <span>$" + this.nextOutwitPot + "</span> - Next Bonus: <span>$" + this.bonusPot + "</span></h4>";
	
	tempOutwitContent += "<h2>" + this.question + "</h2><table class=\"outwitResults\">";
	
	for (var i = 0; i < this.answers.length; i++)
	{
		var tempImages = "";
		
		if (this.contestantAnswerId == this.answers[i].id)
		{
			tempImages += "<a href=\"/shoppers/" + this.contestant.nickname + "\">";
			tempImages += "<img src=\"";
			tempImages += this.contestant.smallAvatarUri;
			tempImages += "\" alt=\"";
			tempImages += this.contestant.nickname;
			tempImages += "\" /></a>";
		}
		
		if (!this.contestantToken && this.userChoice == this.answers[i].id)
		{
			tempImages += "<a href=\"/shoppers" + window.nickname + "\">";
			tempImages += "<img src=\"";
			tempImages += window.smallAvatarUri;
			tempImages += "\" alt=\"";
			tempImages += window.nickname;
			tempImages += "\" /></a>";
		}
		
		tempOutwitContent += "<tr><td valign=\"top\">" + tempImages + "</td><td valign=\"top\" class=\"percent\">" + this.answers[i].votePct.toFixed(2) + "%</td><td valign=\"top\">" + this.answers[i].text + "</td></tr>";
	}
	
	tempOutwitContent += "</table>";
	
	this.template.update("outwitContent", tempOutwitContent);
	this.template.update("outwitPot", this.outwitPot);
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
}

CompletedOutwit.prototype.cleanUp = function()
{
	window.liveObjectTimer.cleanUp();
}

CompletedOutwit.prototype.initializeTimer = function()
{
if (this.nextSegmentType == "deal")
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">Next deal starts in</div><div class="timerText" id="liveObjectTimer"></div>';
}
else
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">The show ends in</div><div class="timerText" id="liveObjectTimer"></div>';

}
	window.liveObjectTimer.syncTimer(secondsRemaining(this.soldOutAt, this.currentTime, this.duration));
}

http://www.jellyfish.com/smack/javascripts/outwit/OutwitRegistration.js

OutwitRegistration = function(json_hash)
{	
	this.typeIdentifier = "OutwitRegistration";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate([
		"<div id=\"deal\" class=\"outwit\">",
			"<div id=\"outwitCoins\">WIN<div id=\"outwitPot\">$","__outwitPot","</div></div>",
			"<img src=\"outwit_title.gif\" alt=\"Outwit the Smack\" />",
			"__outwitContent",
		"</div>"
	]);

 	this.draw();
}

OutwitRegistration.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
		return;
	else
	{
		globalCleanUp();
		window.liveObject = this;
	}
	
	this.template.update("outwitPot", "2300");
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
}

OutwitRegistration.prototype.cleanUp = function()
{

}

http://www.jellyfish.com/smack/javascripts/outwit/LiveOutwitRegistration.js

LiveOutwitRegistration = function(json_hash)
{	
	this.typeIdentifier = "LiveOutwitRegistration";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate([
		"<div id=\"outwitHeader\" class=\"outwit\">",
			"<ul id=\"outwitMenuList\">",
				"<li><a href=\"javascript:toggleClass('outwitHeader','outwit');toggleClass('deal','outwit');\" title=\"Outwit the Smack\" id=\"outwitMenu\" class=\"highlighted\"></a></li>",
				"<li><a href=\"javascript:toggleClass('outwitHeader','outwitRules');toggleClass('deal','outwitRules');\" title=\"Rules and FAQs\" id=\"outwitRulesMenu\"></a></li>",
			"</ul>",
		"</div>",
		"<div id=\"deal\" class=\"outwit\">",
			"<div id=\"outwitContainer\">",
				"<div id=\"outwitCoins\">WIN<div id=\"outwitPot\">$","__outwitPot","</div></div>",
				"<img src=\"/smack/images/smacktv/outwit/outwit_title.gif\" alt=\"Outwit the Smack\" />",
				"<div class=\"clearFloat\"> </div><br /><br />",
				"__outwitContent",
			"</div><br /><div id=\"outwitError\"></div>",
			"<div id=\"outwitRulesContainer\">",
"<h3>Rules &amp; How To Play</h3><p>Think you can outwit the Smack?  Now's your chance...In between certain Smack deals, we will start playing the Outwit the Smack game.</p><h3>Random Contestant</h3><p>The game will start when Smack Daddy selects a random person from the Smack show audience.  (Actually, a computer generated process will randomly select a shopper from a list of smack show participants that respond to the opt-in message at the start of the game). One lucky contestant will then \"come on down\" for their turn on the Smack stage.</p><h3>One Question, Everyone Plays</h3><p>Both the contestant and the rest of the smack audience will be presented with the same question with multiple choice answers. Everyone will then have a short time to put in a blind answer to the question, trying to \"outwit\" the rest of the smack community by selecting the <b>LEAST POPULAR</b> answer. If you select the least popular answer, you win, whether you are the contestant or in the studio audience.</p><h3>What Do I Win?</h3><p>Winning contestants will receive 3 guru points and a cash prize identified at the start of the game. Winning audience members will receive 1 guru point to build towards the monthly guru points race. The cash prize will be a progressive pot: if an Outwit contestant loses, we will add to the cash amount for the next game (typically in increments of $10).</p><h3>What About Ties?</h3><p>Ties will still win.  That's just the way Smack Daddy rolls.  If we receive an exact number of responses to the same answer, either answer will count towards a win.</p><p><a href=\"/smacktv/aboutOutwit\">Now a Word from Carl's Lawyers &mdash; Official Rules</a></p>",
			"</div>",
		"</div>"
	]);

 	this.draw();
}

LiveOutwitRegistration.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
		return;
	else
	{
		globalCleanUp();
		window.liveObject = this;
		this.initializeTimer();
	}
	
	var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	if (this.sponsor != null)  {
		var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor.type == "c")  {
			$("logosContainer").innerHTML = sponsorHTML;
		} else  {
			$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
		}
	} else  {
		$("logosContainer").innerHTML = noSponsorHTML;
	}

	if(this.segmentSponsor != null)  {
		if (this.segmentSponsor.logoUri.match(/.swf/) == null)
			$('segmentSponsorContainer').innerHTML = '<br/><a href="/redirect/outbound?u=' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
		else
			$('segmentSponsorContainer').innerHTML = '<br/><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object>';
		$('segmentSponsorContainer').style.display = '';
	} else  {
		$('segmentSponsorContainer').style.display = 'none';
		$('segmentSponsorContainer').innerHTML = '';
	}
	
	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}

	document.getElementById("messageCenter").className = "messageLiveDeal";
	var tempOutwitContent = "<h1>Feel Lucky?</h1><p>Do you have what it takes to outwit the smack? The game begins when we have enough players.</p><hr /><div id=\"thanksContainer\"></div>";
	
	if (this.userIsIn)
	{
		tempOutwitContent += "<img src=\"/smack/images/smacktv/outwit/imInChecked.gif\" alt=\"I'm in\" />";
	}
	else
	{
		tempOutwitContent += "<div id=\"captchaBox\"<p>To opt in, please submit the code you see displayed below:</p>";
		tempOutwitContent += "</div>";

		tempOutwitContent += "<form action=\"/smacktv/register_for_outwit?encrypted_u_id="+ window.eu +"&outwit_id="+ this.outwitId + "\"";
		tempOutwitContent += "id=\"captcha\"";
		tempOutwitContent += "method=\"post\"";
		tempOutwitContent += "onsubmit=\"new Ajax.Request('/smacktv/register_for_outwit?encrypted_u_id=";
		tempOutwitContent += window.eu;
		tempOutwitContent += "&outwit_id=";
		tempOutwitContent += this.outwitId;
		tempOutwitContent += "', {asynchronous:true, evalScripts:true, onComplete: window.liveObject.registerResponse, parameters:Form.serialize(this) }); return false;\">";
		
		tempOutwitContent += "<img src=\"/img/captcha/";
		tempOutwitContent += this.captcha.uri;
		tempOutwitContent += "\" alt=\"Enter this into the text box to continue\" />";
		
		tempOutwitContent += "<input type=\"hidden\" name=\"captcha_id\" value=\""+ this.captcha.id + "\" />";
		tempOutwitContent += "<input type=\"text\" name=\"captcha_answer\" id=\"captcha_answer\"value=\"\" />";
		
		tempOutwitContent += "<input type=\"submit\" value=\"\" id=\"outwitIn\" />";
		tempOutwitContent += "</form><div class=\"clearFloat\"> </div>";
	}
	
	this.template.update("outwitContent", tempOutwitContent);
	
	this.template.update("outwitPot", this.outwitPot);
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
}

LiveOutwitRegistration.prototype.cleanUp = function()
{
	window.liveObjectTimer.cleanUp();
}

LiveOutwitRegistration.prototype.initializeTimer = function()
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">You must decide in:</div><div class="timerText" id="liveObjectTimer"></div>';
	
	window.liveObjectTimer.syncTimer(secondsRemaining(this.startedAt, this.currentTime, this.duration));
}

LiveOutwitRegistration.prototype.registerResponse = function(response)
{
	if (window.liveObject instanceof LiveOutwitRegistration)  {
	  var responseObj = eval('(' + response.responseText + ')');
	  if (responseObj.success)  {
  	    $("captcha").style.display = "none";
  	    $("captchaBox").style.display = "none";
  	    $('outwitError').style.display = 'none';
	    $("thanksContainer").innerHTML = "<img src=\"/smack/images/smacktv/outwit/imInChecked.gif\" alt=\"I'm in\" />";
	  } else  {
	    $('outwitError').innerHTML = responseObj.msg;
	    $('outwitError').style.display = 'block';
	  }
	} 

}
LiveOutwitRegistration.prototype.thanks = function(response)
{
	$("imInToggle").style.display = "none";
	$("thanksContainer").innerHTML = "<img src=\"/smack/images/smacktv/outwit/imInChecked.gif\" alt=\"I'm in\" />";
}

http://www.jellyfish.com/smack/javascripts/outwit/CompletedOutwitRegistration.js

CompletedOutwitRegistration = function(json_hash)
{	
	this.typeIdentifier = "CompletedOutwitRegistration";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate([
		"<div id=\"outwitHeader\" class=\"outwit\">",
			"<ul id=\"outwitMenuList\">",
				"<li><a href=\"javascript:toggleClass('outwitHeader','outwit');toggleClass('deal','outwit');\" title=\"Outwit the Smack\" id=\"outwitMenu\" class=\"highlighted\"></a></li>",
				"<li><a href=\"javascript:toggleClass('outwitHeader','outwitRules');toggleClass('deal','outwitRules');\" title=\"Rules and FAQs\" id=\"outwitRulesMenu\"></a></li>",
			"</ul>",
		"</div>",
		"<div id=\"deal\" class=\"outwit\">",
			"<div id=\"outwitContainer\">",
				"<div id=\"outwitCoins\">WIN<div id=\"outwitPot\">$","__outwitPot","</div></div>",
				"<img src=\"/smack/images/smacktv/outwit/outwit_title.gif\" alt=\"Outwit the Smack\" />",
				"<div class=\"clearFloat\"> </div><br /><br />",
				"__outwitContent",
			"</div>",
			"<div id=\"outwitRulesContainer\">",
"<h3>Rules &amp; How To Play</h3><p>Think you can outwit the Smack?  Now's your chance...In between certain Smack deals, we will start playing the Outwit the Smack game.</p><h3>Random Contestant</h3><p>The game will start when Smack Daddy selects a random person from the Smack show audience.  (Actually, a computer generated process will randomly select a shopper from a list of smack show participants that respond to the opt-in message at the start of the game). One lucky contestant will then \"come on down\" for their turn on the Smack stage.</p><h3>One Question, Everyone Plays</h3><p>Both the contestant and the rest of the smack audience will be presented with the same question with multiple choice answers. Everyone will then have a short time to put in a blind answer to the question, trying to \"outwit\" the rest of the smack community by selecting the <b>LEAST POPULAR</b> answer. If you select the least popular answer, you win, whether you are the contestant or in the studio audience.</p><h3>What Do I Win?</h3><p>Winning contestants will receive 3 guru points and a cash prize identified at the start of the game. Winning audience members will receive 1 guru point to build towards the monthly guru points race. The cash prize will be a progressive pot: if an Outwit contestant loses, we will add to the cash amount for the next game (typically in increments of $10).</p><h3>What About Ties?</h3><p>Ties will still win.  That's just the way Smack Daddy rolls.  If we receive an exact number of responses to the same answer, either answer will count towards a win.</p><p><a href=\"/smacktv/aboutOutwit\">Now a Word from Carl's Lawyers &mdash; Official Rules</a></p>",
			"</div>",
		"</div>"
	]);
	
	this.charactersArray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
	this.outputArray = ["A","A","A","A","A","A","A","A","A","A"];
	this.characterLimit = 10;
	this.cylonTimer;
	this.timerSpeed = 50;
	this.updatePosition = 0;
	this.headingLeft = true;
	this.contestantSet = false;
	this.contestantName = "";
	
	this.randomizeCharacterCache = this.randomizeCharacter;
 	this.draw();
}

CompletedOutwitRegistration.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
	{
		if (this.contestantNickname != null)
		{
			window.liveObject.contestantName = this.contestantNickname;
			window.liveObject.contestantSet = true;
		}
		return;
	}
	else
	{
		globalCleanUp();
		window.liveObject = this;
	}
	
	var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	if (this.sponsor != null)  {
		var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor.type == "c")  {
			$("logosContainer").innerHTML = sponsorHTML;
		} else  {
			$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
		}
	} else  {
		$("logosContainer").innerHTML = noSponsorHTML;
	}

	if(this.segmentSponsor != null)  {
		if (this.segmentSponsor.logoUri.match(/.swf/) == null)
			$('segmentSponsorContainer').innerHTML = '<br/><a href="/redirect/outbound?u=' + this.segmentSponsor.uri + '" target="_blank"><img src="/img' + this.segmentSponsor.logoUri + '" /></a>';
		else
			$('segmentSponsorContainer').innerHTML = '<br/><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="sponsorFlash"><param name="MOVIE" value="/img' + this.segmentSponsor.logoUri + '"><param name="PLAY" value="true"><param name="LOOP" value="true"><param name="QUALITY" value="high"><param name="SCALE" value="SHOWALL"><embed name="sponsorFlash" src="/img' + this.segmentSponsor.logoUri + '" play="true" loop="true" quality="high" scale="SHOWALL" swLiveConnect="true" pluginspace="http://www.macromedia.com/go/flashplayer/"></embed></object>';
		$('segmentSponsorContainer').style.display = '';
	} else  {
		$('segmentSponsorContainer').style.display = 'none';
		$('segmentSponsorContainer').innerHTML = '';
	}
	
	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}
	
	document.getElementById("messageCenter").className = "messageLiveDeal";
	
	if (this.enoughToPlay)
	{
		if (this.contestantNickname != null)
		{
			var tempOutwitContent = "<h1>Selecting a Contestant:</h1><div id=\"playerName\" style=\"color:#ffffff;\">" + this.contestantNickname + "</div>";
			this.initializeTimer();
		}
		else
		{
			var tempOutwitContent = "<h1>Selecting a Contestant:</h1><div id=\"playerName\"></div>";
			this.initializeTimer();
		}
	}
	else
	{
		var tempOutwitContent = "<h1>Movin' On</h1><p>Sorry we didn't have enough people to play, maybe next time you should tell your friends.</p>";
		this.initializeTimer2();
	}
	
	this.template.update("outwitContent", tempOutwitContent);
	
	this.template.update("outwitPot", this.outwitPot);
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
	
	if (this.contestantNickname == null && this.enoughToPlay)
		this.cylonTimer = setInterval(this.randomizeCharacterCache.bind(this), this.timerSpeed);
}

CompletedOutwitRegistration.prototype.cleanUp = function()
{
	window.liveObjectTimer.cleanUp();
	clearInterval(this.cylonTimer);
}

CompletedOutwitRegistration.prototype.initializeTimer = function()
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">Outwit Starts In:</div><div class="timerText" id="liveObjectTimer"></div>';
	
	window.liveObjectTimer.syncTimer(secondsRemaining(this.soldOutAt, this.currentTime, this.duration));
}

CompletedOutwitRegistration.prototype.initializeTimer2 = function()
{
	
if (this.nextSegmentType == "deal")
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">Next deal starts in</div><div class="timerText" id="liveObjectTimer"></div>';
}
else
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">The show ends in</div><div class="timerText" id="liveObjectTimer"></div>';

}
	
	window.liveObjectTimer.syncTimer(secondsRemaining(this.soldOutAt, this.currentTime, this.duration));
}

CompletedOutwitRegistration.prototype.randomizeCharacter = function()
{
	this.outputArray[this.updatePosition] = this.charactersArray[Math.floor(Math.random() * this.charactersArray.length)];
	
	document.getElementById("playerName").innerHTML = this.outputArray.join("");
	
	if (this.updatePosition == this.characterLimit - 1)
		this.headingLeft = false;
		
	if (this.updatePosition == 0)
	{
		this.headingLeft = true;
		if (this.contestantSet)
		{
			clearInterval(this.cylonTimer);
			this.cylonTimer = setInterval(this.revealContestant.bind(this), this.timerSpeed);
			return;
		}
	}
			
	if (this.headingLeft)
		this.updatePosition++;
	else
		this.updatePosition--;
}
		
CompletedOutwitRegistration.prototype.revealContestant = function()
{
	if (this.updatePosition < this.contestantName.length)
	{
		this.outputArray[this.updatePosition] = this.contestantName.charAt(this.updatePosition);
		document.getElementById("playerName").innerHTML = this.outputArray.join("");
	}
	else if (this.updatePosition < this.outputArray.length)
	{
		this.outputArray[this.updatePosition] = "&nbsp;&nbsp;";
		document.getElementById("playerName").innerHTML = this.outputArray.join("");
	}
	
	this.updatePosition++;
	
	if (this.updatePosition >= this.contestantName.length && this.updatePosition >= this.outputArray.length)
	{
		clearInterval(this.cylonTimer);
		$("playerName").style.color = "#ffffff";
	}
}

http://www.jellyfish.com/smack/javascripts/showpreview/ShowPreview.js

ShowPreview = function(json_hash)
{	
	this.typeIdentifier = "ShowPreview";
	
	for(var i in json_hash)
	{
		this[i] = json_hash[i];
	}
	
	this.template = new HypertextTemplate([
		"<div id=\"deal\" class=\"preview\">",
			"<div id=\"previewContent\">",
				"<h1>Coming Up Next:</h1>",
				"<img src=\"/smack/images/smacktv/showpreview/icons/","__imageUri","\" />",
				"<h2>","__name","</h2>",
				"<h3>","__startTime","</h3>",
				"<img src=\"/smack/images/smacktv/showpreview/smacktoo.gif\" />",
			"</div>",
		"</div>"
	]);

 	this.draw();
}

ShowPreview.prototype.draw = function()
{
	if (window.liveObject && window.liveObject.typeIdentifier == this.typeIdentifier)
		return;
	else
	{
		globalCleanUp();
		window.liveObject = this;
		this.initializeTimer();
	}

	var noSponsorHTML = "<a href=\"/smacktv\"><img src=\"/smack/images/smacktv/header/smack_shopping_logo.gif\" alt=\"Smack Shopping by Jellyfish\" /></a>";
	if (this.sponsor != null)
	{
		var sponsorHTML = "<a href=\"/redirect/outbound?u=" + this.sponsor.uri + "\" target=\"_blank\"><img src=\"/img" + this.sponsor.logoUri + "\" alt=\"Smack Shopping by Jellyfish\" /></a>";
		if (this.sponsor.type == "c")  {
			$("logosContainer").innerHTML = sponsorHTML;
		} else  {
			$('logosContainer').innerHTML = noSponsorHTML + sponsorHTML;
		}
	}
	else
	{
		$("logosContainer").innerHTML = noSponsorHTML;
	}
	
	$('segmentSponsorContainer').style.display = 'none';
	$('segmentSponsorContainer').innerHTML = '';
	
	if (this.iconUri != null)
	{
		$("showTitleImage").innerHTML ="<img src=\"/smack/images/smacktv/homepage/icons/" + this.iconUri + "\" />";
		$("showName").innerHTML = this.showName;
		$("showStartTime").innerHTML = this.timeSlot;
		$("showTitle").style.display = "block";
	}
	else
	{
		$("showTitle").style.display = "none";
	}
	
	this.template.update("imageUri", this.imageUri);
	this.template.update("name", this.name);
	this.template.update("startTime", this.startTime);
	
	document.getElementById("liveObjectContainer").innerHTML = this.template.renderHTML();
}

ShowPreview.prototype.cleanUp = function()
{
	window.liveObjectTimer.cleanUp();
}

ShowPreview.prototype.initializeTimer = function()
{
	document.getElementById("messageCenter").innerHTML = '<div class="messageText">Next Show Starts In:</div><div class="timerText" id="liveObjectTimer"></div>';
	
	window.liveObjectTimer.syncTimer(this.duration);
}

http://www.jellyfish.com/javascripts/moo.fx.js

/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
Sunday, March 05, 2006
v 1.2.3
*/

var fx = new Object();
//base
fx.Base = function(){};
fx.Base.prototype = {
	setOptions: function(options) {
	this.options = {
		duration: 500,
		onComplete: '',
		transition: fx.sinoidal
	}
	Object.extend(this.options, options || {});
	},

	step: function() {
		var time  = (new Date).getTime();
		if (time >= this.options.duration+this.startTime) {
			this.now = this.to;
			clearInterval (this.timer);
			this.timer = null;
			if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
		}
		else {
			var Tpos = (time - this.startTime) / (this.options.duration);
			this.now = this.options.transition(Tpos) * (this.to-this.from) + this.from;
		}
		this.increase();
	},

	custom: function(from, to) {
		if (this.timer != null) return;
		this.from = from;
		this.to = to;
		this.startTime = (new Date).getTime();
		this.timer = setInterval (this.step.bind(this), 13);
	},

	hide: function() {
		this.now = 0;
		this.increase();
	},

	clearTimer: function() {
		clearInterval(this.timer);
		this.timer = null;
	}
}

//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.el.style.overflow = "hidden";
		this.iniWidth = this.el.offsetWidth;
		this.iniHeight = this.el.offsetHeight;
		this.setOptions(options);
	}
});

fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {	
	increase: function() {
		this.el.style.height = this.now + "px";
	},

	toggle: function() {
		if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
		else this.custom(0, this.el.scrollHeight);
	}
});

fx.Width = Class.create();
Object.extend(Object.extend(fx.Width.prototype, fx.Layout.prototype), {	
	increase: function() {
		this.el.style.width = this.now + "px";
	},

	toggle: function(){
		if (this.el.offsetWidth > 0) this.custom(this.el.offsetWidth, 0);
		else this.custom(0, this.iniWidth);
	}
});

//fader
fx.Opacity = Class.create();
fx.Opacity.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.now = 1;
		this.increase();
		this.setOptions(options);
	},

	increase: function() {
		if (this.now == 1 && (/Firefox/.test(navigator.userAgent))) this.now = 0.9999;
		this.setOpacity(this.now);
	},
	
	setOpacity: function(opacity) {
		if (opacity == 0 && this.el.style.visibility != "hidden") this.el.style.visibility = "hidden";
		else if (this.el.style.visibility != "visible") this.el.style.visibility = "visible";
		if (window.ActiveXObject) this.el.style.filter = "alpha(opacity=" + opacity*100 + ")";
		this.el.style.opacity = opacity;
	},

	toggle: function() {
		if (this.now > 0) this.custom(1, 0);
		else this.custom(0, 1);
	}
});

//transitions
fx.sinoidal = function(pos){
	return ((-Math.cos(pos*Math.PI)/2) + 0.5);
	//this transition is from script.aculo.us
}
fx.linear = function(pos){
	return pos;
}
fx.cubic = function(pos){
	return Math.pow(pos, 3);
}
fx.circ = function(pos){
	return Math.sqrt(pos);
}

http://www.jellyfish.com/javascripts/moo.fx.pack.js

/*
moo.fx pack, effects extensions for moo.fx.
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE
for more info visit (http://moofx.mad4milk.net).
Friday, April 14, 2006
v 1.2.4
*/

//smooth scroll
fx.Scroll = Class.create();
fx.Scroll.prototype = Object.extend(new fx.Base(), {
	initialize: function(options) {
		this.setOptions(options);
	},

	scrollTo: function(el){
		var dest = Position.cumulativeOffset($(el))[1];
		var client = window.innerHeight || document.documentElement.clientHeight;
		var full = document.documentElement.scrollHeight;
		var top = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
		if (dest+client > full) this.custom(top, dest - client + (full-dest));
		else this.custom(top, dest);
	},

	increase: function(){
		window.scrollTo(0, this.now);
	}
});

//text size modify, now works with pixels too.
fx.Text = Class.create();
fx.Text.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.setOptions(options);
		if (!this.options.unit) this.options.unit = "em";
	},

	increase: function() {
		this.el.style.fontSize = this.now + this.options.unit;
	}
});

//composition effect: widht/height/opacity
fx.Combo = Class.create();
fx.Combo.prototype = {
	setOptions: function(options) {
		this.options = {
			opacity: true,
			height: true,
			width: false
		}
		Object.extend(this.options, options || {});
	},

	initialize: function(el, options) {
		this.el = $(el);
		this.setOptions(options);
		if (this.options.opacity) {
			this.o = new fx.Opacity(el, options);
			options.onComplete = null;
		}
		if (this.options.height) {
			this.h = new fx.Height(el, options);
			options.onComplete = null;
		}
		if (this.options.width) this.w = new fx.Width(el, options);
	},
	
	toggle: function() { this.checkExec('toggle'); },

	hide: function(){ this.checkExec('hide'); },
	
	clearTimer: function(){ this.checkExec('clearTimer'); },
	
	checkExec: function(func){
		if (this.o) this.o[func]();
		if (this.h) this.h[func]();
		if (this.w) this.w[func]();
	},
	
	//only if width+height
	resizeTo: function(hto, wto) {
		if (this.h && this.w) {
			this.h.custom(this.el.offsetHeight, this.el.offsetHeight + hto);
			this.w.custom(this.el.offsetWidth, this.el.offsetWidth + wto);
		}
	},

	customSize: function(hto, wto) {
		if (this.h && this.w) {
			this.h.custom(this.el.offsetHeight, hto);
			this.w.custom(this.el.offsetWidth, wto);
		}
	}
}

fx.Accordion = Class.create();
fx.Accordion.prototype = {
	setOptions: function(options) {
		this.options = {
			delay: 100,
			opacity: false
		}
		Object.extend(this.options, options || {});
	},

	initialize: function(togglers, elements, options) {
		this.elements = elements;
		this.setOptions(options);
		var options = options || '';
		this.fxa = [];
		if (options && options.onComplete) options.onFinish = options.onComplete;
		elements.each(function(el, i){
			options.onComplete = function(){
				if (el.offsetHeight > 0) el.style.height = '1%';
				if (options.onFinish) options.onFinish(el);
			}
			this.fxa[i] = new fx.Combo(el, options);
			this.fxa[i].hide();
		}.bind(this));

		togglers.each(function(tog, i){
			if (typeof tog.onclick == 'function') var exClick = tog.onclick;
			tog.onclick = function(){
				if (exClick) exClick();
				this.showThisHideOpen(elements[i]);
			}.bind(this);
		}.bind(this));
	},

	showThisHideOpen: function(toShow){
		this.elements.each(function(el, j){
			if (el.offsetHeight > 0 && el != toShow) this.clearAndToggle(el, j);
			if (el == toShow && toShow.offsetHeight == 0) setTimeout(function(){this.clearAndToggle(toShow, j);}.bind(this), this.options.delay);
		}.bind(this));
	},

	closeMeUp: function(toShow){
		this.elements.each(function(el, j){
			if (el.offsetHeight > 0 && el != toShow) this.clearAndToggle(el, j);
		}.bind(this));
	},

	clearAndToggle: function(el, i){
		this.fxa[i].clearTimer();
		this.fxa[i].toggle();
	}
}

var Remember = new Object();
Remember = function(){};
Remember.prototype = {
	initialize: function(el, options){
		this.el = $(el);
		this.days = 365;
		this.options = options;
		this.effect();
		var cookie = this.readCookie();
		if (cookie) {
			this.fx.now = cookie;
			this.fx.increase();
		}
	},

	//cookie functions based on code by Peter-Paul Koch
	setCookie: function(value) {
		var date = new Date();
		date.setTime(date.getTime()+(this.days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = this.el+this.el.id+this.prefix+"="+value+expires+"; path=/";
	},

	readCookie: function() {
		var nameEQ = this.el+this.el.id+this.prefix + "=";
		var ca = document.cookie.split(';');
		for(var i=0;c=ca[i];i++) {
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return false;
	},

	custom: function(from, to){
		if (this.fx.now != to) {
			this.setCookie(to);
			this.fx.custom(from, to);
		}
	}
}

fx.RememberHeight = Class.create();
fx.RememberHeight.prototype = Object.extend(new Remember(), {
	effect: function(){
		this.fx = new fx.Height(this.el, this.options);
		this.prefix = 'height';
	},
	
	toggle: function(){
		if (this.el.offsetHeight == 0) this.setCookie(this.el.scrollHeight);
		else this.setCookie(0);
		this.fx.toggle();
	},
	
	resize: function(to){
		this.setCookie(this.el.offsetHeight+to);
		this.fx.custom(this.el.offsetHeight,this.el.offsetHeight+to);
	},

	hide: function(){
		if (!this.readCookie()) {
			this.fx.hide();
		}
	}
});

fx.RememberText = Class.create();
fx.RememberText.prototype = Object.extend(new Remember(), {
	effect: function(){
		this.fx = new fx.Text(this.el, this.options);
		this.prefix = 'text';
	}
});

//useful for-replacement
Array.prototype.iterate = function(func){
	for(var i=0;i<this.length;i++) func(this[i], i);
}
if (!Array.prototype.each) Array.prototype.each = Array.prototype.iterate;

//Easing Equations (c) 2003 Robert Penner, all rights reserved.
//This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html.

//expo
fx.expoIn = function(pos){
	return Math.pow(2, 10 * (pos - 1));
}
fx.expoOut = function(pos){
	return (-Math.pow(2, -10 * pos) + 1);
}

//quad
fx.quadIn = function(pos){
	return Math.pow(pos, 2);
}
fx.quadOut = function(pos){
	return -(pos)*(pos-2);
}

//circ
fx.circOut = function(pos){
	return Math.sqrt(1 - Math.pow(pos-1,2));
}
fx.circIn = function(pos){
	return -(Math.sqrt(1 - Math.pow(pos, 2)) - 1);
}

//back
fx.backIn = function(pos){
	return (pos)*pos*((2.7)*pos - 1.7);
}
fx.backOut = function(pos){
	return ((pos-1)*(pos-1)*((2.7)*(pos-1) + 1.7) + 1);
}

//sine
fx.sineOut = function(pos){
	return Math.sin(pos * (Math.PI/2));
}
fx.sineIn = function(pos){
	return -Math.cos(pos * (Math.PI/2)) + 1;
}
fx.sineInOut = function(pos){
	return -(Math.cos(Math.PI*pos) - 1)/2;
}

http://www.jellyfish.com/smack/javascripts/showSchedule.js

function showBox(content, top, left, width, height, direction)
{
	$("smackInfoBox").style.display = "none";
	
	if (direction == "left")
	{
		$("smackInfoBox").style.left = left - 195 + "px";
		$("smackInfoBox").className = "left";
	}
	else
	{
		$("smackInfoBox").className = "right";
		$("smackInfoBox").style.left = left + width - 25 + "px";	
	}
	
	$("smackInfoBox").style.top = top + 5 + "px";
	
	
	//$("contentBox").innerHTML = scheduleContent[content] + "<a href='#' onclick='javascript:hideBox();return false;'>(close)</a>";
	
	$("contentBox").innerHTML = content;
	$("smackInfoBox").style.display = "block";
}

function hideBox()
{
	$("smackInfoBox").style.display = "none";
}


/* CONTENT EXAMPLE

"<img src=\"/smack/images/smacktv/homepage/icons/toysgames_small.gif\" /><h2>Toys and Games</h2><h3>7:00am - 12:00pm</h3><p>Looking for the hottest toy or a classic board game? Show items will include everything from fire engines to dolls to educational toys to action figures and much more.</p>"

*/

http://www.jellyfish.com/javascripts/encloses.js?1182806929

function encloses(me, node)
{
	if (node == null)
		return false;
	else if (node == me)
		return true;
	else
		return encloses(me, node.parentNode);
}

function openFlyout(flyoutID, myTop, myLeft)
{
	$(flyoutID).style.top = myTop + "px";
	$(flyoutID).style.left = myLeft + "px";
	$(flyoutID).style.display = "block";
}

function closeFlyout(triggerID, flyoutID, myEvent)
{	
	if ( !encloses($(triggerID), myEvent.relatedTarget || myEvent.toElement) && !encloses($(flyoutID),myEvent.relatedTarget || myEvent.toElement) )
		$(flyoutID).style.display = "none";
}

function closeFlyoutSimple(flyoutID, myEvent)
{	
	if ( !encloses($(flyoutID),myEvent.relatedTarget || myEvent.toElement) )
		$(flyoutID).style.display = "none";
}

http://www.jellyfish.com/javascripts/effects.js?1158153585

// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// See scriptaculous.js for full license.  

// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';  
  if(this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if(this.slice(0,1) == '#') {  
      if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if(this.length==7) color = this.toLowerCase();  
    }  
  }  
  return(color.length==7 ? color : (arguments[0] || this));  
}

/*--------------------------------------------------------------------------*/

Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
}

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
}

Element.setContentZoom = function(element, percent) {
  element = $(element);  
  Element.setStyle(element, {fontSize: (percent/100) + 'em'});   
  if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
}

Element.getOpacity = function(element){  
  var opacity;
  if (opacity = Element.getStyle(element, 'opacity'))  
    return parseFloat(opacity);  
  if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))  
    if(opacity[1]) return parseFloat(opacity[1]) / 100;  
  return 1.0;  
}

Element.setOpacity = function(element, value){  
  element= $(element);  
  if (value == 1){
    Element.setStyle(element, { opacity: 
      (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 
      0.999999 : null });
    if(/MSIE/.test(navigator.userAgent))  
      Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});  
  } else {  
    if(value < 0.00001) value = 0;  
    Element.setStyle(element, {opacity: value});
    if(/MSIE/.test(navigator.userAgent))  
     Element.setStyle(element, 
       { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
                 'alpha(opacity='+value*100+')' });  
  }
}  
 
Element.getInlineOpacity = function(element){  
  return $(element).style.opacity || '';
}  

Element.childrenWithClassName = function(element, className, findFirst) {
  var classNameRegExp = new RegExp("(^|\\s)" + className + "(\\s|$)");
  var results = $A($(element).getElementsByTagName('*'))[findFirst ? 'detect' : 'select']( function(c) { 
    return (c.className && c.className.match(classNameRegExp));
  });
  if(!results) results = [];
  return results;
}

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};

/*--------------------------------------------------------------------------*/

Array.prototype.call = function() {
  var args = arguments;
  this.each(function(f){ f.apply(this, args) });
}

/*--------------------------------------------------------------------------*/

var Effect = {
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if(/MSIE/.test(navigator.userAgent)) tagifyStyle += ';zoom:1';
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if(child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            Builder.node('span',{style: tagifyStyle},
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if(((typeof element == 'object') || 
        (typeof element == 'function')) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || {});
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || {});
    Effect[element.visible() ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

var Effect2 = Effect; // deprecated

/* ------------- transitions ------------- */

Effect.Transitions = {}

Effect.Transitions.linear = function(pos) {
  return pos;
}
Effect.Transitions.sinoidal = function(pos) {
  return (-Math.cos(pos*Math.PI)/2) + 0.5;
}
Effect.Transitions.reverse  = function(pos) {
  return 1-pos;
}
Effect.Transitions.flicker = function(pos) {
  return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
}
Effect.Transitions.wobble = function(pos) {
  return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
}
Effect.Transitions.pulse = function(pos) {
  return (Math.floor(pos*10) % 2 == 0 ? 
    (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
}
Effect.Transitions.none = function(pos) {
  return 0;
}
Effect.Transitions.full = function(pos) {
  return 1;
}

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
  initialize: function() {
    this.effects  = [];
    this.interval = null;
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = (typeof effect.options.queue == 'string') ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    
    if(!this.interval) 
      this.interval = setInterval(this.loop.bind(this), 40);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if(this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    this.effects.invoke('loop', timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if(typeof queueName != 'string') return queueName;
    
    if(!this.instances[queueName])
      this.instances[queueName] = new Effect.ScopedQueue();
      
    return this.instances[queueName];
  }
}
Effect.Queue = Effect.Queues.get('global');

Effect.DefaultOptions = {
  transition: Effect.Transitions.sinoidal,
  duration:   1.0,   // seconds
  fps:        25.0,  // max. 25fps due to Effect.Queue implementation
  sync:       false, // true for combining
  from:       0.0,
  to:         1.0,
  delay:      0.0,
  queue:      'parallel'
}

Effect.Base = function() {};
Effect.Base.prototype = {
  position: null,
  start: function(options) {
    this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn + (this.options.duration*1000);
    this.event('beforeStart');
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if(timePos >= this.startOn) {
      if(timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if(this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / (this.finishOn - this.startOn);
      var frame = Math.round(pos * this.options.fps * this.options.duration);
      if(frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  render: function(pos) {
    if(this.state == 'idle') {
      this.state = 'running';
      this.event('beforeSetup');
      if(this.setup) this.setup();
      this.event('afterSetup');
    }
    if(this.state == 'running') {
      if(this.options.transition) pos = this.options.transition(pos);
      pos *= (this.options.to-this.options.from);
      pos += this.options.from;
      this.position = pos;
      this.event('beforeUpdate');
      if(this.update) this.update(pos);
      this.event('afterUpdate');
    }
  },
  cancel: function() {
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
}

Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if(effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    // make this work on IE on elements without 'layout'
    if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout))
      this.element.setStyle({zoom: 1});
    var options = Object.extend({
      from: this.element.getOpacity() || 0.0,
      to:   1.0
    }, arguments[1] || {});
    this.start(options);
  },
  update: function(position) {
    this.element.setOpacity(position);
  }
});

Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Bug in Opera: Opera returns the "real" position of a static element or
    // relative element that does not have top/left explicitly set.
    // ==> Always set top and left for position relative elements in your stylesheets 
    // (to 0 if you do not need them) 
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
    if(this.options.mode == 'absolute') {
      // absolute movement, so we need to calc deltaX and deltaY
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    this.element.setStyle({
      left: this.options.x  * position + this.originalLeft + 'px',
      top:  this.options.y  * position + this.originalTop  + 'px'
    });
  }
});

// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};

Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
  initialize: function(element, percent) {
    this.element = $(element)
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || {});
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');
    
    this.originalStyle = {};
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%'].each( function(fontSizeType) {
      if(fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if(this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = {};
    if(this.options.scaleX) d.width = width + 'px';
    if(this.options.scaleY) d.height = height + 'px';
    if(this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if(this.elementPositioning == 'absolute') {
        if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if(this.options.scaleY) d.top = -topd + 'px';
        if(this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if(this.element.getStyle('display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = {
      backgroundImage: this.element.getStyle('background-image') };
    this.element.setStyle({backgroundImage: 'none'});
    if(!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if(!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    this.start(arguments[1] || {});
  },
  setup: function() {
    Position.prepare();
    var offsets = Position.cumulativeOffset(this.element);
    if(this.options.offset) offsets[1] += this.options.offset;
    var max = window.innerHeight ? 
      window.height - window.innerHeight :
      document.body.scrollHeight - 
        (document.documentElement.clientHeight ? 
          document.documentElement.clientHeight : document.body.clientHeight);
    this.scrollStart = Position.deltaY;
    this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
  },
  update: function(position) {
    Position.prepare();
    window.scrollTo(Position.deltaX, 
      this.scrollStart + (position*this.delta));
  }
});

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  var options = Object.extend({
  from: element.getOpacity() || 1.0,
  to:   0.0,
  afterFinishInternal: function(effect) { 
    if(effect.options.to!=0) return;
    effect.element.hide();
    effect.element.setStyle({opacity: oldOpacity}); 
  }}, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Appear = function(element) {
  element = $(element);
  var options = Object.extend({
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  to:   1.0,
  // force Safari to render floated elements properly
  afterFinishInternal: function(effect) {
    effect.element.forceRerendering();
  },
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from);
    effect.element.show(); 
  }}, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { opacity: element.getInlineOpacity(), position: element.getStyle('position') };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) {
        effect.effects[0].element.setStyle({position: 'absolute'}); },
      afterFinishInternal: function(effect) {
         effect.effects[0].element.hide();
         effect.effects[0].element.setStyle(oldStyle); }
     }, arguments[1] || {})
   );
}

Effect.BlindUp = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0, 
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide();
        effect.element.undoClipping();
      } 
    }, arguments[1] || {})
  );
}

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, 
    Object.extend({ scaleContent: false, 
      scaleX: false,
      scaleFrom: 0,
      scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
      restoreAfterFinish: true,
      afterSetup: function(effect) {
        effect.element.makeClipping();
        effect.element.setStyle({height: '0px'});
        effect.element.show(); 
      },  
      afterFinishInternal: function(effect) {
        effect.element.undoClipping();
      }
    }, arguments[1] || {})
  );
}

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  return new Effect.Appear(element, { 
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { 
          effect.element.makePositioned();
          effect.element.makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide();
          effect.element.undoClipping();
          effect.element.undoPositioned();
          effect.element.setStyle({opacity: oldOpacity});
        }
      })
    }
  });
}

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned(); 
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide();
          effect.effects[0].element.undoPositioned();
          effect.effects[0].element.setStyle(oldStyle);
        } 
      }, arguments[1] || {}));
}

Effect.Shake = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element, 
      { x:  20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
        effect.element.undoPositioned();
        effect.element.setStyle(oldStyle);
  }}) }}) }}) }}) }}) }});
}

Effect.SlideDown = function(element) {
  element = $(element);
  element.cleanWhitespace();
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = $(element.firstChild).getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.firstChild.makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping();
      effect.element.setStyle({height: '0px'});
      effect.element.show(); },
    afterUpdateInternal: function(effect) {
      effect.element.firstChild.setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping(); 
      // IE will crash if child is undoPositioned first
      if(/MSIE/.test(navigator.userAgent)){
        effect.element.undoPositioned();
        effect.element.firstChild.undoPositioned();
      }else{
        effect.element.firstChild.undoPositioned();
        effect.element.undoPositioned();
      }
      effect.element.firstChild.setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || {})
  );
}
  
Effect.SlideUp = function(element) {
  element = $(element);
  element.cleanWhitespace();
  var oldInnerBottom = $(element.firstChild).getStyle('bottom');
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    restoreAfterFinish: true,
    beforeStartInternal: function(effect) {
      effect.element.makePositioned();
      effect.element.firstChild.makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping();
      effect.element.show(); },  
    afterUpdateInternal: function(effect) {
      effect.element.firstChild.setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); },
    afterFinishInternal: function(effect) {
      effect.element.hide();
      effect.element.undoClipping();
      effect.element.firstChild.undoPositioned();
      effect.element.undoPositioned();
      effect.element.setStyle({bottom: oldInnerBottom}); }
   }, arguments[1] || {})
  );
}

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, 
    { restoreAfterFinish: true,
      beforeSetup: function(effect) {
        effect.element.makeClipping(effect.element); },  
      afterFinishInternal: function(effect) {
        effect.element.hide(effect.element); 
        effect.element.undoClipping(effect.element); }
  });
}

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) {
      effect.element.hide();
      effect.element.makeClipping();
      effect.element.makePositioned();
    },
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'});
               effect.effects[0].element.show(); 
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping();
               effect.effects[0].element.undoPositioned();
               effect.effects[0].element.setStyle(oldStyle); 
             }
           }, options)
      )
    }
  });
}

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned();
           effect.effects[0].element.makeClipping(); },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide();
           effect.effects[0].element.undoClipping();
           effect.effects[0].element.undoPositioned();
           effect.effects[0].element.setStyle(oldStyle); }
       }, options)
  );
}

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || {};
  var oldOpacity = element.getInlineOpacity();
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 3.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
}

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  Element.makeClipping(element);
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) {
        effect.element.hide();
        effect.element.undoClipping(); 
        effect.element.setStyle(oldStyle);
      } });
  }}, arguments[1] || {}));
};

['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom',
 'collectTextNodes','collectTextNodesIgnoreClass','childrenWithClassName'].each( 
  function(f) { Element.Methods[f] = Element[f]; }
);

Element.Methods.visualEffect = function(element, effect, options) {
  s = effect.gsub(/_/, '-').camelize();
  effect_class = s.charAt(0).toUpperCase() + s.substring(1);
  new Effect[effect_class](element, options);
  return $(element);
};

Element.addMethods();

http://www.jellyfish.com/javascripts/FlashTimer.js

/*
FlashTimer.js by Jason Karolczak-Konen
Dependant on prototype.js
Copyright 2007 Jellyfish.com
Latest Revision: 2007-03-01
*/

FlashTimer = Class.create();
FlashTimer.prototype =
{
	initialize: function(myId, mySeconds, myArgs)
	{
		//Nostradomus code
		this.do_predictive_fetch = false;
      this.attempted_switchover = false;
		
		//function caching
		this.decrementTimeCache = this.decrementTime;
		this.specialCaseFormattingCache = this.specialCaseFormatting;
		
		this.elementName = myId;
		this.secondsLeft = (mySeconds < 0) ? 0 : mySeconds;
		this.outputPattern = (typeof myArgs == "undefined") ? "DD:##0HH:##0MM:##0SS.S" : (typeof myArgs.outputPattern != "undefined") ? myArgs.outputPattern : "DD:##0HH:##0MM:##0SS.S";
		this.endText = (typeof myArgs == "undefined") ? "Here it comes" : (typeof myArgs.endText != "undefined") ? myArgs.endText : "Here it comes";
		this.preCode = (typeof myArgs == "undefined") ? "" : (typeof myArgs.preCode != "undefined") ? myArgs.preCode : "";
		this.postCode = (typeof myArgs == "undefined") ? "" : (typeof myArgs.postCode != "undefined") ? myArgs.postCode : "";

		this.truncateTimer = (this.outputPattern.match("##") == "##") ? true : false;
		
		this.showMilliseconds = (this.outputPattern.match("SS.S") == "SS.S") ? true : false;
		if (this.showMilliseconds)
			this.outputPattern = this.outputPattern.replace("SS.S", "SS");
		
		this.leadingHours = (this.outputPattern.match("0HH") == "0HH") ? true : false;
		if (this.leadingHours)
			this.outputPattern = this.outputPattern.replace("0HH", "HH");
			
		this.leadingMinutes = (this.outputPattern.match("0MM") == "0MM") ? true : false;
		if (this.leadingMinutes)
			this.outputPattern = this.outputPattern.replace("0MM", "MM");
			
		this.leadingSeconds = (this.outputPattern.match("0SS") == "0SS") ? true : false; 
		if (this.leadingSeconds)
			this.outputPattern = this.outputPattern.replace("0SS", "SS");
		
		this.leadingZeros = (this.leadingSeconds || this.leadingMinutes || this.leadingHours) ? true : false;
		
		if (this.truncateTimer)
			this.outputPattern = this.outputPattern.split("##");
		
		this.decrement = (this.showMilliseconds) ? 0.1 : 1;
		this.speed = 1000 * this.decrement;
	},
	
	startTimer: function()
	{
		this.syncTimer()
	},
	
	syncTimer: function(newSecondsLeft)
	{
		if (newSecondsLeft == undefined || newSecondsLeft > 0)  {
		
			this.cleanUp();
			this.secondsLeft = typeof newSecondsLeft != "undefined" ? newSecondsLeft : this.secondsLeft;
	
			this.days = Math.floor(this.secondsLeft / 86400);
			this.hours = Math.floor((this.secondsLeft - this.days * 86400) / 3600);
			this.minutes = Math.floor((this.secondsLeft - this.days * 86400 - this.hours * 3600) / 60);
			this.seconds = this.secondsLeft - this.days * 86400 - this.hours * 3600 - this.minutes * 60;
			
			if (this.days > 0)
			{
				this.daysZero = false;
				this.hoursZero = false;
				this.minutesZero = false;
				this.secondsZero = false;
			}
			else
			{
				this.daysZero = true;
			
				if (this.hours > 0)
				{
					this.hoursZero = false;
					this.minutesZero = false;
					this.secondsZero = false;
				}
				else
				{
					this.hoursZero = true;
					if (this.minutes > 0)
					{
						this.minutesZero = false;
						this.secondsZero = false;
					}
					else
					{
						this.minutesZero = true;
						if (this.secondsLeft > 0)
							this.secondsZero = false;
						else
							this.secondsZero = true;
					}		
				}
			}
		
			this.specialCaseFormatting();
			this.updateTimer(this);
			this.timer = setInterval(this.updateTimer.bind(this), this.speed );
		}
	},
	
	decrementTime: function()
	{		
		if (this.seconds > 0)
			this.seconds = Math.round((this.seconds - this.decrement) * 10) / 10;
		else
		{			
			if (this.minutes > 0)
			{
				this.minutes--;
				this.seconds = 60 - this.decrement;
			}
			else
			{									
				if (this.hours > 0)
				{
					this.hours--;
					this.minutes = 59;
					this.seconds = 60 - this.decrement;
				}
				else
				{														
					if (this.days > 0)
					{
						this.days--;
						this.hours = 23;
						this.minutes = 59;
						this.seconds = 60 - this.decrement;
					}
				}
			}
		}
		
		if (this.days <= 0)
			this.daysZero = true;
		
		if (this.daysZero && this.hours <= 0)
			this.hoursZero = true;
		
		if (this.hoursZero && this.minutes <= 0)	
			this.minutesZero = true;
		
		if (this.minutesZero && this.seconds <= 0)
			this.secondsZero = true;
				
		this.specialCaseFormattingCache();
	},
	
	updateTimer: function()
	{	
		if (this.truncateTimer)
		{
			this.output = "";
		
			if (!this.daysZero)
				if (this.days == 1)
					this.output += this.outputPattern[0];
				else
					this.output += this.outputPattern[0];
		
			if (!this.hoursZero)
				if (this.hours == 1)
					this.output += this.outputPattern[1];
				else
					this.output += this.outputPattern[1];
				
			if (!this.minutesZero)
				if (this.minutes == 1)
					this.output += this.outputPattern[2];
				else
					this.output += this.outputPattern[2];
				
			if ((this.seconds >= 1 && this.seconds < 2) && (!this.minutesZero || !this.showMilliseconds))
				this.output += this.outputPattern[3];
			else
				this.output += this.outputPattern[3];
		}
		else
			this.output = this.outputPattern;

		if (!this.secondsZero)
		{			
			this.output = this.output.replace("DD", this.days);
			this.output = this.output.replace("HH", this.hoursText);
			this.output = this.output.replace("MM", this.minutesText);
			this.output = this.output.replace("SS", this.secondsText);

			if ( $(this.elementName) )
				$(this.elementName).innerHTML = this.preCode + this.output + this.postCode;
			else
			{
				this.killTimer();
				return;
			}
			this.decrementTimeCache();
		}
		else
			this.killTimer();
	},
	
	killTimer: function(displayText)
	{
		if ( $(this.elementName) )
			$(this.elementName).innerHTML = typeof displayText != "undefined" ? displayText : this.endText;
		clearInterval(this.timer);
		
		if (this.do_predictive_fetch && ! this.attempted_switchover)
		{
			this.attempted_switchover = true;
			window.s.doSwitchOver();
		}
	},
	
	cleanUp: function()
	{
		clearInterval(this.timer);
	},
	
	specialCaseFormatting: function()
	{			
		if (this.showMilliseconds && this.minutesZero)
		{
			if ((Math.round((this.seconds - this.decrement) * 10) / 10) % 1 == 0)
				this.secondsText = Math.floor(this.seconds) + ".0";
			else
				this.secondsText = Math.round((this.seconds - this.decrement) * 10) / 10;
		}
		else
			this.secondsText = Math.floor(this.seconds);
			
		if (this.leadingZeros)
		{	
			if (this.leadingHours && this.hours < 10 && (!this.daysZero || !this.truncateTimer))
				this.hoursText = "0" + this.hours;
			else
				this.hoursText = this.hours;
		
			if (this.leadingMinutes && this.minutes < 10 && (!this.hoursZero || !this.truncateTimer))
				this.minutesText = "0" + this.minutes;
			else
				this.minutesText = this.minutes;
				
			if (this.leadingSeconds && this.seconds < 10 && (!this.minutesZero || !this.truncateTimer))
				this.secondsText = "0" + this.secondsText;
		}
		else
		{
			this.hoursText = this.hours;
			this.minutesText = this.minutes;
		}
	}
}

http://www.jellyfish.com/smack/javascripts/smack_wheel/v2wheel.js

/*
smackwheel.js by Jason Karolczak-Konen
Dependant on prototype.js
Copyright 2007 Jellyfish.com
Latest Revision: 2007-04-13
*/

SmackWheelV2 = Class.create();
SmackWheelV2.prototype =
{
	initialize: function()
	{
		//function caching
		this.incrementWheelCache = this.incrementWheel;
		this.callBeepCache = this.callBeep;
			
		// this.prizesAndOdds = this.prizes;
		
		this.odds = new Array();
		
		this.beeperPosition = 50; //Position of the beeper line relative to the frame that's around it
		this.stepOneSlowdown = 0.75; //Percent slowdown before flagging "ok" to perform final stop
		this.stepThreeSlowdown = 1; //Percent slowdown before stop
		this.increment = 20; //Amount, in pixels, to move the panels down each frame
		this.spinTime = 35; //Time, in milliseconds, between frames
		this.prizePosition = 3; //Position pointer to show next prize in the array
		this.timer; //Timer to start and stop the spinner
		this.wheelStopping = false; //Flag to say the stop button has been pressed
		this.prizeAtTop = false; //Flag to start slowdown when the stopping prize has been rendered for the first time
		this.finalSlowdown = false; //Flag set to initiate the final slowdown
		this.wheelStopped = false; //Flag set when the wheel has stopped
		this.movieName = "clickerFlash"; //Name of the beeper Flash movie
		this.movieURL = "/smack/release_sound2.swf"; //URL for the beeper Flash movie
		this.panelDivs = ""; //Holds string of panel DIVs for HTML output
		this.mute = false; //Tells if the mute button has been pressed or not

		//(AJAX) Array of prizes (holds the URL for the image for each panel in order of placement on the wheel)
		this.prizeSrcPrefix = "/smack/images/smacktv/wheel/tiles/";
		this.prizes;

		//(AJAX) Percent slowdown before flagging "ok" for final panel ready (range between 0.05 (fast) and 0.25 (slow))
		this.stepTwoSlowdown;

		//(AJAX) Prize index to stop at
		this.stopAt;
		
		//Tests for modern browser support (IE7, Mozilla, Firefox, Safari, Opera 9+) and enables the PNG wheel overlay
		this.pngOverlay = "";
		if ( typeof document.body.style.maxHeight != "undefined" )
			this.pngOverlay = "<div id=\"wheelOverlay\"></div>";
			
		this.imageCache = new Array();
		
		this.panelIDs = new Array();
		this.panelPositions = new Array();
	},
	
	//Returns the correct reference to a given Flash movie (browser specific)
	flashMovieReference: function(movieName)
	{
		if (navigator.appName.indexOf ("Microsoft") !=-1)
			return window[movieName];
		else
			return document[movieName];
	},

	//Tests to see if a given Flash movie has loaded
	flashMovieLoaded: function (movieName)
	{
		//Catched bug in Opera if Flash isn't installed
		try
		{
			if (typeof(movieName) != "undefined")
				return movieName.PercentLoaded() == 100;
			else
				return false;
		}
		catch(e)
		{
			return false;
		}
	},

	//Plays the given Flash movie
	playFlashMovie: function(movieName)
	{
		if (this.flashMovieLoaded(this.flashMovieReference(movieName)))
			this.flashMovieReference(movieName).Play();
	},
	
	//Starts spinning the wheel
	startWheel: function()
	{
		for (var i = 0; i < this.prizes.length; i++)
		{
			//Set initial panel positions
			$(this.panelIDs[i]).style.top = this.panelPositions[i] + "px";
			
			//Set initial panel images
			// console.log(this.prizes[i]);
			$("Image" + i).setAttribute("src", this.prizes[i]);
		}

		//Start incrementing the wheel
		//this.incrementWheel();
		this.incrementWheelCache();
	},

	//Keeps the wheel spinning and modifies the increment if the wheel should be stopped	
	incrementWheel: function()
	{	
		if (!this.wheelStopped)
		{
		
		//Resets the bottom panel when it moves offscreen
		for (var i = 0; i < this.prizes.length; i++)
		{
			if (this.panelPositions[i] > (90 * this.prizes.length) - 91)
			{
				this.panelPositions[i] += -90 * this.prizes.length;
				if ( this.wheelStopping && i == this.stopAt )
					this.prizeAtTop = true;
				if ( this.wheelStopping && this.increment < 5 && i == this.stopAt )
					this.finalSlowdown = true;
			}	
		}
				
		//Moves the beeper position tracker between 0 and 90
		if (this.beeperPosition > 89)
		{
			//this.callBeep();
			this.callBeepCache();
			this.beeperPosition += -90;
		}
		
		//Calculate new panel positions
		for (i = 0; i < this.prizes.length; i++)
			this.panelPositions[i] += Math.floor(this.increment);
		
		//Increment the new beeper position tracker
		this.beeperPosition += Math.floor(this.increment);
		
		//Moves all panels to new positions
		for (i = 0; i < this.prizes.length; i++)
			if (this.panelPositions[i] <= 270 + this.increment)
				$(this.panelIDs[i]).style.top = this.panelPositions[i] + "px";
		
		//Stops the wheel at the correct prize and kills the timer
		if ( this.finalSlowdown && this.panelPositions[this.stopAt] > 86 )
		{
			clearTimeout(this.timer);
			this.wheelStopped = true;

			return;
		}

		//Slows down the wheel after the stop button has been pressed
//		if ( this.wheelStopping && this.prizeAtTop )
		if ( this.wheelStopping )
		{
			//Slows down spin when stop button has been pressed and the increment is already slow but before the stop panel has been rendered
			if ( this.increment < 5 && !this.finalSlowdown)
				this.increment -= this.increment * (this.stepTwoSlowdown * 0.01);
			//Slows down spin when stop button has been pressed but before the stop panel has been rendered
			else if ( this.finalSlowdown )
				this.increment -= this.increment * (this.stepThreeSlowdown * 0.01);
			//Slows down the spin when the stop button has been pressed
			else
				this.increment -= this.increment * (this.stepOneSlowdown * 0.01);

			//Fail safe if increment is ever below 1 (pixel) set the increment to 1 so the wheel doesn't stop	
			if ( this.increment < 1 )
				this.increment = 1;
		}

		//Continues spinning the wheel
		//this.timer = setTimeout(this.incrementWheel.bind(this), this.spinTime );
		this.timer = setTimeout(this.incrementWheelCache.bind(this), this.spinTime );
		}
	},

	//Stops the wheel when the stop button has been pressed
	stopWheel: function(prizeIndex)
	{
		this.wheelStopping = true;
		this.stopAt = prizeIndex;
	},
	
	//Writes a stopped wheel at a given index
	drawStoppedWheel: function(myPrize)
	{
		$(this.panelIDs[myPrize]).style.top = "87px";
		$("Image" + myPrize).setAttribute("src", this.prizes[myPrize]);
		
		if (myPrize == 0)
		{
			$(this.panelIDs[this.prizes.length - 1]).style.top = "-3px";
			$("Image" + (this.prizes.length - 1)).setAttribute("src", this.prizes[this.prizes.length - 1]);
			
			$(this.panelIDs[myPrize + 1]).style.top = "177px";
			$("Image" + (myPrize + 1)).setAttribute("src", this.prizes[myPrize + 1]);
		}
		else if (myPrize == this.prizes.length - 1)
		{
			$(this.panelIDs[myPrize - 1]).style.top = "-3px";
			$("Image" + (myPrize - 1)).setAttribute("src", this.prizes[myPrize - 1]);
			
			$(this.panelIDs[0]).style.top = "177px";
			$("Image0").setAttribute("src", this.prizes[0]);
		}
		else
		{
			$(this.panelIDs[myPrize - 1]).style.top = "-3px";
			$("Image" + (myPrize - 1)).setAttribute("src", this.prizes[myPrize - 1]);
			
			$(this.panelIDs[myPrize + 1]).style.top = "177px";
			$("Image" + (myPrize + 1)).setAttribute("src", this.prizes[myPrize + 1]);
		}
	},
	
	//Writes HTML to show the Smack Wheel and it's container DIV at the given ID
	drawWheel: function(drawAtId, prizesArray, randomSlowdown)
	{
		//Set variables based on AJAX response
		this.prizes = prizesArray;
		this.stepTwoSlowdown = randomSlowdown;
		
		for (var i = 0; i < this.prizes.length; i++)
		{
		  // console.log(this.prizes[i].imageUri);
		  this.odds.push(this.prizes[i]);
	    this.prizes[i] = this.prizeSrcPrefix + this.prizes[i].imageUri;
	    this.panelDivs += "<div id=\"Panel" + i + "\" class=\"wheelPanel\"><img src=\"/smack/images/smackwheel/trans.gif\" id=\"Image" + i + "\" alt=\"Prize\" /></div>";
			this.panelIDs[i] = "Panel" + i;
			this.panelPositions[i] = 90 * i;
		}
		
		//Set last panel to -90 so that it's next in line
		this.panelPositions[this.prizes.length - 1] = -90;

		var htmlToOutput = "<div id=\"wheelContainer\">"
		+ "<div id=\"wheelFrameContainer\">"
		+ "<div id=\"wheelFrame\">"
		+ this.pngOverlay
		+ this.panelDivs
		+ "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"0\" height=\"0\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab\" id=\"clickerFlash\"><param name=\"MOVIE\" value=\"" + this.movieURL + "\"><param name=\"PLAY\" value=\"false\"><param name=\"LOOP\" value=\"false\"><param name=\"QUALITY\" value=\"high\"><param name=\"SCALE\" value=\"SHOWALL\"><embed name=\"clickerFlash\" src=\"" + this.movieURL + "\" width=\"0\" height=\"0\" play=\"false\" loop=\"false\" quality=\"high\" scale=\"SHOWALL\" swLiveConnect=\"true\" pluginspace=\"http://www.macromedia.com/go/flashplayer/\"></embed></object>"
		+ "</div></div></div>"  

		$(drawAtId).innerHTML = htmlToOutput;
	},
	
	//Starts the Flash movie that plays a beep when the wheel is in position
	callBeep: function()
	{
		if ( !window.mute )
			this.playFlashMovie(this.movieName);
	},
	
	toggleMuteSound: function() 
	{
		if(window.mute) 
		{ 
			window.mute = false; 
			$('mute_sound_toggle').className = 'wheelMute';
			new Ajax.Request('/smacktv/toggleMuteSound', {asynchronous:true});
		} 
		else 
		{ 
			window.mute = true; 
			$('mute_sound_toggle').className = 'wheelUnMute';
			new Ajax.Request('/smacktv/toggleMuteSound', {asynchronous:true, parameters:'mute=1'});
		}
	},
	
	doSmackWheelResponse: function(gameObj)  {
        if (gameObj.p != undefined)
        {
    	  if (window.sw == undefined || window.sw == null)
              window.sw = new SmackWheel();
          if (gameObj.pw == undefined)  {
              window.sw.drawWheel('deal_of_the_day', gameObj.p, gameObj.sd, gameObj.su, gameObj.slu);
              stv.winners_circle = false;
          } else  {
              window.sw.drawWheel('deal_of_the_day', gameObj.p, gameObj.sd, gameObj.su, gameObj.slu);
              window.sw.drawStoppedWheel(gameObj.pw);
              window.sw.pw = gameObj.pw;
              stv.winners_circle = true;
          }
          if (gameObj.pw == undefined)  {
              if (gameObj.c) {
                  
              } else {
                  
              }
          } else  {
              
              if(gameObj.bf == false) {
                
              } else {
                
              }
              
              if(gameObj.nst == "deal") {
                
              } else if(gameObj.nst == "game")  {
                
              } else if (gameObj.nst == "vote")  {
                
              } else {
                
              }
          }
          if (gameObj.cd)  {
              //swt = new CountdownTimer($('swTimer'), gameObj.cd, "", "no more time ");
              //swt.start();
          } else if (gameObj.wcd)  {
              //swt = new CountdownTimer($('wcTimer'), gameObj.wcd, "", "");
              //swt.start();
          }
        } else  {
          
          if ($('stop_wheel_btn').className == 'stopButtonLocked')  {

          } else  {

          }
          
          window.sw.stopWheel(gameObj.pw);
          window.sw.pw = gameObj.pw;
          stv.winners_circle = true;
          //swt = new CountdownTimer($('wcTimer'), gameObj.wcd, "", "");
          //swt.start();
        }
        DealGuess.prototype.writeGuessingClosed();
	},
	
	doStopWheelRequest: function()  {
	   x = new ajax ('/smacktv/stopWheel', {
	       postBody: 'segid='+stv.segment_id,
	       onComplete: this.doStopWheelResponse}
	   );
	},
	
	doStopWheelResponse: function(request) {
	   var responseObj = eval('('+request.responseText+')');
	   if (eval(responseObj.s))  {
    	   $('stop_wheel_btn').className = 'stopButtonFinal';
    	   window.sw.stopWheel(responseObj.pw);
	   }
	},
	
	preloadImages: function(imageArray)  {
	
        SmackWheel.prototype.imageCache = new Array();
        	
	    for (var i = 0; i < imageArray.length; i++)  {
	        SmackWheel.prototype.imageCache[i]=new Image;
	        SmackWheel.prototype.imageCache[i].src = "/smack/images/smacktv/wheel/tiles/" + imageArray[i];
	    }    
	},
	
	killWheel: function()
	{
		clearTimeout(this.timer);
		this.wheelStopped = true;
	}
	
}

http://www.jellyfish.com/smack/javascripts/Shusher.js

Shusher = function() {}
Shusher.prototype = {
  shush: function(user_id, state, comment_id) {
    x = new Ajax.Request("/smacktv/shush?user=" + user_id + "&state=" + state + "&comment_id=" +comment_id, {asynchronous: true, method: "get", parameters: ""});
  },
  toggle: function(comment_text_id) {
    if($(comment_text_id).style.display == 'none') {
      $(comment_text_id).style.display = 'block';
    } else {
      $(comment_text_id).style.display = 'none';
    }
  }
}

Inline Script from http://www.jellyfish.com/smacktv/channel/1

		var sl;
		
		window.onload = function()
		{
		
		
		  
		  window.sdq_points = 0;
		  window.sdq_points_old = 0;
		  window.sdqChange = 0;
		  window.sdq_first_time = true;
		  
		  window.liveObjectTimer = new FlashTimer("liveObjectTimer", 0);
		  
		  
		  window.mute = true;
		  
		  shusher = new Shusher();
			
				s = new SmackTVController(1);
				s.start();
			
			
      
		}
		function globalResponseHandler(xhr)
		{
			s.handleResponse(xhr.responseText);
  		}
  		      
		function globalFailSafe()
		{
			s.doFailSafe();
		}
		
		function globalUpdateSDQ()
		{
			if (window.sdq_points > window.sdq_points_old && !window.sdq_first_time )
				window.sdqChange = window.sdq_points - window.sdq_points_old;
			else
			{
				window.sdqChange = 0;
				window.sdq_first_time = false;
			}
			$("sdqBurst").innerHTML = "+" + window.sdqChange;
			window.sdq_points_old = window.sdq_points;
			
			updateSDQmeter(window.sdq_points);
			
			new Effect.Highlight($("sdqBurstOutter"), { endcolor:"#2e4a5d", startcolor:"#ffffff" } );			
		}
		
		function updateSDQmeter(myPoints)
		{
			var points = String(myPoints);
			var leadingSpaces = 6 - points.length;
			var temp;
			for (var i = 0; i < leadingSpaces; i++)
				points = "B" + points;
			
			var temp = points.split("");
			for (var r = 1; r <= 6; r++)
			{			
				$("sdq" + r).className = "num" + temp[r - 1];
			}
		}
		      
		function globalCleanUp()
		{
			if (window.liveObject != null)
			{
    	  		window.liveObject.cleanUp();
			}
		}
		function globalSetMostRecentCommentId(most_recent_comment_id) {
		  s.most_recent_comment_id = most_recent_comment_id;
		}
		
  		  window.eu = 'wgYYri---o2u___ulTwFQFqZlA';
		  window.shopperPageName = 'mindstorm';
		  
		    window.avatarUri = '/img/shoppers/avatars/wgYYri---o2u___ulTwFQFqZlA.jpg';
		    window.smallAvatarUri = '/img/shoppers/avatars/wgYYri---o2u___ulTwFQFqZlA_s.jpg';
		  
  		
    		window.nickname = 'Mindstorm';
   		
		 

	

Inline Script from http://www.jellyfish.com/smacktv/channel/1

  try {
    window.secureBuyUrl = ["https://", location.host].join('');
  } catch(e) {
    window.secureBuyUrl = "";
  }

Inline Script from http://www.jellyfish.com/smacktv/channel/1

var _hbEC=0,_hbE=new Array;function _hbEvent(a,b){b=_hbE[_hbEC++]=new Object();b._N=a;b._C=0;return b;}
var hbx=_hbEvent("pv");hbx.vpc="HBX0200u";hbx.gn="ehg-jellyfish.hitbox.com";

//BEGIN EDITABLE SECTION
//CONFIGURATION VARIABLES
hbx.acct="DM560623L7SR62EN3";//ACCOUNT NUMBER(S)
hbx.pn= _hbxStrip("smacktv - channel - The Daily Smack");//PAGE NAME(S)
hbx.mlc= _hbxStrip("");//MULTI-LEVEL CONTENT CATEGORY
hbx.pndef="title";//DEFAULT PAGE NAME
hbx.ctdef="full";//DEFAULT CONTENT CATEGORY

//OPTIONAL PAGE VARIABLES
//ACTION SETTINGS
hbx.fv="";//FORM VALIDATION MINIMUM ELEMENTS OR SUBMIT FUNCTION NAME
hbx.lt="auto";//LINK TRACKING
hbx.dlf="n";//DOWNLOAD FILTER
hbx.dft="n";//DOWNLOAD FILE NAMING
hbx.elf="n";//EXIT LINK FILTER

//SEGMENTS AND FUNNELS
hbx.seg="";//VISITOR SEGMENTATION
hbx.fnl="";//FUNNELS

//CAMPAIGNS
hbx.cmp="";//CAMPAIGN ID
hbx.cmpn="";//CAMPAIGN ID IN QUERY
hbx.dcmp="";//DYNAMIC CAMPAIGN ID
hbx.dcmpn="";//DYNAMIC CAMPAIGN ID IN QUERY
hbx.dcmpe="";//DYNAMIC CAMPAIGN EXPIRATION
hbx.dcmpre="";//DYNAMIC CAMPAIGN RESPONSE EXPIRATION
hbx.hra="";//RESPONSE ATTRIBUTE
hbx.hqsr="";//RESPONSE ATTRIBUTE IN REFERRAL QUERY
hbx.hqsp="";//RESPONSE ATTRIBUTE IN QUERY
hbx.hlt="";//LEAD TRACKING
hbx.hla="";//LEAD ATTRIBUTE
hbx.gp="";//CAMPAIGN GOAL
hbx.gpn="";//CAMPAIGN GOAL IN QUERY
hbx.hcn="";//CONVERSION ATTRIBUTE
hbx.hcv="";//CONVERSION VALUE
hbx.cp="null";//LEGACY CAMPAIGN
hbx.cpd="";//CAMPAIGN DOMAIN

//CUSTOM VARIABLES
hbx.ci= _hbxStrip("binary10@gmail.com");//CUSTOMER ID
hbx.hc1=_hbxStrip("");//SEARCH TERM
hbx.hc2=_hbxStrip("binary10@gmail.com");//CUSTOMER ID
hbx.hc3="";//CUSTOM 3
hbx.hc4="";//CUSTOM 4
hbx.hrf="";//CUSTOM REFERRER
hbx.pec="";//ERROR CODES

//INSERT CUSTOM EVENTS
function _hbxStrip(a){
  a = a.split("|").join("");
  a = a.split("&").join("");
  a = a.split("'").join("");
  a = a.split("#").join("");
  a = a.split("$").join("");
  a = a.split("%").join("");
  a = a.split("^").join("");
  a = a.split("*").join("");
  a = a.split(":").join("");
  a = a.split("!").join("");
  a = a.split("<").join("");
  a = a.split(">").join("");
  a = a.split("~").join("");
  a = a.split(";").join("");
  a = a.split(" ").join("+");
  return a;   
}
//END EDITABLE SECTION

//REQUIRED SECTION. CHANGE "YOURSERVER" TO VALID LOCATION ON YOUR WEB SERVER (HTTPS IF FROM SECURE SERVER)

http://www.jellyfish.com/js/hbx.js

//hbx.js,HBX2.0,COPYRIGHT 1997-2006 WEBSIDESTORY,INC. ALL RIGHTS RESERVED. U.S.PATENT No.6,393,479B1 & 6,766,370. INFO:http://websidestory.com/privacy
/* INSERT CUSTOM EVENT CODE HERE */
// custom code for 2.0 release to send linkviews on page view until the backend is ready
// remove this code block if we want to send linkViews as a separate request
function _hbOnPrePV(req){
    for(var a=0;a<_IL(document.links);a++){
        if(_lvid.length+_lvpos.length<_lvm)
            _LV(document.links[a]);
        else break;
    }
    _ar += "&lv.id="+_lvid+"&lv.pos="+_lvpos;
    _lvl=-1; 
}

/* DO NOT CHANGE BELOW THIS LINE */
var _vjs="HBX0201.03u";
var _dl=".exe,.zip,.wav,.wmv,.mp3,.mov,.mpg,.avi,.doc,.pdf,.xls,.ppt,.gz,.bin,.hqx,.dmg";
function _NA(a){return new Array(a?a:0)}
var _mn=_hbq="",_hbA=_NA(),_hud="undefined",_huf="function",_ec=_if=_ll=_hec=_hfs=_hfc=_hfa=_ic=_pC=_fc=_pv=0,_hbi=_hbs=new Image(),_hbin=_NA(),_pA=_NA();
_lvid=_lvpos=_lvl="";_hbE=_D("hbE")?_hbE:"";_hbEC=_D("hbEC")?_hbEC:0;var _ex="expires=Wed, 1 Jan 2020 00:00:00 GMT",_lvm=300,_lidt="lid",_lpost="lpos",
_pum=_erf=_hif=0;
function _D(v){return(typeof eval("window._"+v)!=_hud)?eval("window._"+v):""}function _DD(v){return(typeof v!=_hud)?1:0}
function _A(v,c){return escape((_D("lc")=="y"&&_DD(c))?_TL(v):v)}
function _B(){return 0}function _GP(){return (_IL(_D("protocol"))>0)?_protocol+"://":(location.protocol=="https:"?"https://":"http://")}
function _IC(a,b,c){return a.charAt(b)==c?1:0}function _II(a,b,c){return a.indexOf(b,c?c:0)}function _IL(a){return a!=_hud?a.length:0}
function _IF(a,b,c){return a.lastIndexOf(b,c?c:_IL(a))}function _IP(a,b){return a.split(b)}
function _IS(a,b,c){return b>_IL(a)?"":a.substring(b,c!=null?c:_IL(a))}
function _RP(a,b,c,d){d=_II(a,b);if(d>-1){a=_RP(_IS(a,0,d)+","+_IS(a,d+_IL(b),_IL(a)),b,c)}return a}
function _TL(a){return a.toLowerCase()}function _TS(a){return a.toString()}function _TV(){_hbSend()}function _SV(a,b,c){_hbSet(a,b,c)}
function _VS(a,b,c,d){c=['C','P','R'];for(d=0;d<_IL(c);d++){if(_II(""+b,"_"+c[d]+"::")==0)b=eval("_R"+c[d]+"V(_IS(b,4,_IL(b)))")}eval("_"+a+"='"+b+"'")}
function _VC(a,b,c,d){b=_IP(a,",");for(c=0;c<_IL(b);c++){d=_IP(b[c],"|");_VS(d[0],(_D(d[0]))?_D(d[0]):d[1]?d[1]:"")}}
function _VL(a,b){for(a=0;a<_hbEC;a++){_pv=_hbE[a];if(_pv._N=="pv"){for(b in _pv){if(_EE(b)&&typeof _pv[b]!=_huf){_VS(b,_pv[b])}}}}
_VC("pn|PUT+PAGE+NAME+HERE,mlc|CONTENT+CATEGORY,elf|n,dlf|n,dft|n,pndef|title,ctdef|full,cp|null,hcn|")}_VL();
function _ER(a,b,c){if(_erf++==0)_hbi.src=_GP()+_gn+"/HG?hc="+_mn+"&hb="+_A(_acct)+"&hec=1&vjs="+_vjs+"&vpc=ERR&ec=1&err="+
((typeof a=="string")?_A(a+"-"+c):"Unknown");_XT("Error",a);}
function _EE(a){return(a!="_N"&&a!="_C")?1:0}_EV(window,"error",_ER);
function _hbSend(c,a,i){a="";_hec++;for(i in _hbA)if(typeof _hbA[i]!=_huf)a+="&"+i+"="+_hbA[i];_Q(_hbq+"&hec="+_hec+a+_hbSendEV());_hbA=_NA()}
function _hbSet(a,b,c,d,e){d=_II(_hbq,"&"+a+"=");if(d>-1){e=_II(_hbq,"&",d+1);e=e>d?e:_IL(_hbq);if(a=="n"||a=="vcon"){_hbq=_IS(_hbq,0,d)+"&"+a+"="+b+
_IS(_hbq,e);_hec=-1;if(a=="n"){_pn=b}else{_mlc=b}}else{_hbq=_IS(_hbq,0,d)+_IS(_hbq,e)}}if((a!="n")&&(a!="vcon"))_hbA[a]=(c==0)?b:_A(b)}
function _hbRedirect(a,b,c,d,e,f,g){_SV("n",a);_SV("vcon",b);if(_DD(d)&&_IL(d)>0){d=_IC(d,0,"&")?_IS(d,1,_IL(d)):d;e=_IP(d,"&");for(f=0;f<_IL(e);
f++){g=_IP(e[f],"=");_SV(g[0],g[1])}}_TV();if(c!=""){_SV("hec",0);setTimeout("location.href='"+c+"'",500)}}
function _hbSendEV(a,b,c,d,e,f,x,i){a='',c='',e=_IL(_hbE);for(b=0;b<e;b++){c=_hbE[b];for(var d in c){if(_EE(d)&&c[d].match){x=c[d].match(/\[\]/g);
if(x!=null&&_IL(x)>c._C)c._C=_IL(x)}}for(d in c){if(_EE(d)&&c[d].match){x=c[d].match(/\[\]/g);x=(x==null)?0:_IL(x);for(i=x;i<c._C;i++)c[d]+="[]"}}}
for(b=0;b<e;b++){c=_hbE[b];for(f=b+1;f<e;f++){if(_hbE[f]!=null&&c._N==_hbE[f]._N){for(d in c){if(_EE(d)&&_hbE[f]!=null)c[d]+="[]"+_hbE[f][d];
_hbE[f][d]=""}}}for(d in c){if(_EE(d)&&c._N!=""&&c._N!="pv"){a+="&"+c._N+"."+d+"="+_RP(_A(c[d]),"%5B%5D",",")}}}_hbE=_NA();_hbEC=0;return a}
function _hbM(a,b,c,d){_SV('n',a);_SV('vcon',b);if(_IL(c)>0)_SV(c,d);_TV()}
function _hbPageView(p,m){_hec=-1;_hbM(p,m,"")}function _hbExitLink(n){_hbM(_pn,_mlc,"el",n)}function _hbDownload(n){_hbM(_pn,_mlc,"fn",n)}
function _hbVisitorSeg(n,p,m){_SV("n",p);_SV("vcon",m);_SV("seg",n,1);_TV()}function _hbCampaign(n,p,m){_hbM(p,m,"cmp",n)}
function _hbFunnel(n,p,m){_hbM(p,m,"fnl",n)}function _hbGoalPage(n,p,m){_hbM(p,m,"gp",n)}
function _hbLink(a,b,c){_SV("lid",a);if(_DD(b))_SV("lpos",b);_XT("Link","");_TV()}
function _hbForm(a,b,c,d,e,f){if(_DD(c))_hlf=c;_hfs=0,_fa=1,f='Complete',_hfa=0;if(a==0){f='Abandon';_hfa=1}_XT("Form"+f,b)}
function _hbCookie(a,b,c){document.cookie=a+"="+b+";path=/;"+((_DD(c)==1)?"expires="+c:"")}
function _LE(a,b,c,d,e,f,g,h,i,j,k,l){b="([0-9A-Za-z\\-]*\\.)",c=location.hostname,d=a.href,h='',i='';eval("__f=/"+b+"*"+b+"/");if(_DD(__f)){__f.exec(c);
j=(_DD(_elf))?_elf:"";if(j!="n"){if(_II(j,"!")>-1){h=_IS(j,0,_II(j,"!"));i=_IS(j,_II(j,"!")+1,_IL(j))}else{h=j}}k=0;if(_DD(_elf)&&_elf!="n"){
if(_IL(i)){l=_IP(i,",");for(g=0;g<_IL(l);g++)if(_II(d,l[g])>-1)return}if(_IL(h)){l=_IP(h,",");for(g=0;g<_IL(h);g++)if(_II(d,l[g])>-1)k=1}}
if(_II(a.hostname,RegExp.$2)<0||k){	e=_IL(d)-1;return _IC(d,e,'/')?_IS(d,0,e):d}}}
function _LD(a,b,c,d,e,f){b=a.pathname,d='',e='';b=_IS(b,_IF(b,"/")+1,_IL(b));c=(_DD(_dlf))?_dlf:"";if(c!="n"){if(_II(c,"!")>-1){d=","+
_IS(c,0,_II(c,"!"));e=","+_IS(c,_II(c,"!")+1,_IL(c))}else{d=","+c}}f=_II(b,"?");b=(f>-1)?_IS(b,0,f):b;if(_IF(b,".")>-1){f=_IS(b,_IF(b,"."),_IL(b));
if(_II(_dl+d,f)>-1&&_II(e,f)<0){var dl=b;if(_DD(_dft)){if(_dft=="y"&&a.name){dl=a.name}else if(_dft=="full"){dl=a.pathname;if(!_IC(dl,0,'/'))dl='/'+dl
}}return dl}}}
function _LP(a,b){for(b=0;b<_IL(a);b++){if(_IL(_lvl)<_lvm)_LV(a[b]);_EV(a[b],'mousedown',_LT)}}
function _LV(a,b,c){b=_LN(a);c=b[0]+b[1];if(_IL(b[0])){_lvid+=_A(b[0])+",";_lvpos+=_A(b[1])+",";_lvl+=c}}
function _LN(a,b,c,d){b=a.href;b+=a.name?a.name:"";c=_LVP(b,_lidt);d=_LVP(b,_lpost);return[c,d]}
function _LT(e){if((e.which&&e.which==1)||(e.button&&e.button==1)){var a=document.all?window.event.srcElement:this;for(var i=0;i<4;i++){if(a.tagName&&
_TL(a.tagName)!="a"&&_TL(a.tagName)!="area"){a=a.parentElement}}var b=_LN(a),c='',d='';a.lid=b[0];a.lpos=b[1];if(_D("lt")&&_lt!="manual"){if((a.tagName&&
_TL(a.tagName)=="area")){if(!_IL(a.lid)){if(a.parentNode){if(a.parentNode.name)a.lid=a.parentNode.name;else a.lid=a.parentNode.id}}if(!_IL(a.lpos))
a.lpos=a.coords}else{if(_IL(a.lid)<1)a.lid=_LS(a.text?a.text:a.innerText?a.innerText:"");if(!_IL(a.lid)||_II(_TL(a.lid),"<img")>-1)a.lid=_LI(a)}}
if(!_IL(a.lpos)&&_D("lt")=="auto_pos"&&a.tagName&&_TL(a.tagName)!="area"){c=document.links;for(d=0;d<_IL(c);d++){if(a==c[d]){a.lpos=d+1;break}}}
var _f=0,j='',k='',l=(a.protocol)?_TL(a.protocol):"";
if(l&&l!="mailto:"&&l!="javascript:"){j=_LE(a),k=_LD(a);if(_DD(k))a.fn=k;else if(_DD(j))a.el=j}
if(_D("lt")&&_IC(_lt,0,"n")!=1&&_DD(a.lid)&&_IL(a.lid)>0){_SV("lid",a.lid);if(_DD(a.lpos))_SV("lpos",a.lpos);_f=1}if(_DD(a.fn)){_SV("fn",a.fn);_XT("Download",a);_f=2}
else if(_DD(a.el)){_SV("el",a.el);_XT("ExitLink",a);_f=1}if(_f>0){_XT("Link",a);_TV()}}}
function _LVP(a,b,c,d,e){c=_II(a,"&"+b+"=");c=c<0?_II(a,"?"+b+"="):c;if(c>-1){d=_II(a,'&',c+_IL(b)+2);e=_IS(a,c+_IL(b)+2,d>-1?d:_IL(a));
if(!_ec){if(!(_II(e,"//")==0))return e}else return e}return ""}
function _LI(a){var b=""+a.innerHTML,bu=_TL(b),i=_II(bu,"<img");if(bu&&i>-1){eval("__f=/ src\s*=\s*['\"]?([^'\" ]+)['\"]?/i");__f.exec(b);
if(RegExp.$1)b=RegExp.$1}return b}
function _LSP(a,b,c,d){d=_IP(a,b);return d.join(c)}
function _LS(a,b,c,d,e,f,g){c=_D("lim")?_lim:100;b=(_IL(a)>c)?_A(_IS(a,0,c)):_A(a);b=_LSP(b,"%0A","%20");b=_LSP(b,"%0D","%20");b=_LSP(b,"%09","%20");
c=_IP(b,"%20");d=_NA();e=0;for(f=0;f<_IL(c);f++){g=_RP(c[f],"%20","");if(_IL(g)>0){d[e++]=g}}b=d.join("%20");return unescape(b)}
function _EM(a,b,c,d){a=_D("fv");b=_II(a,";"),c=parseInt(a);d=3;if(_TL(a)=="n"){d=999;_fv=""}else if(b>-1){d=_IS(a,0,b);_fv=_IS(a,b+1,_IL(a))}
else if(c>0){d=c;_fv=""}return d}
function _FF(e){var a=(_bnN)?this:_EVO(e);_hlf=(a.lf)?a.lf:""}
function _FU(e){if(_hfs==0&&_IL(_hlf)>0&&_fa==1){_hfs=1;if(_hfc&&!_hfa){_SV("sf","1");_XT("FormComplete",_hfc)}else if(_IL(_hlf)>0){_SV("lf",_hlf);_XT("FormAbandon",_hlf)}
_TV();_hlf="",_hfs=0,_hfc=0}}
function _FO(e){var a=true;if(_DD(this._FS))eval("try{a=this._FS()}catch(e){}");if(a!=false)_hfc=1;return a}
function _FA(a,b,c,d,e,f,g,h,i,ff,fv,s){b=a.forms;ff=new Object();f=_EM();for(c=0;c<_IL(b);c++){ff=b[c],d=0,s=0,e=ff.elements;
g=ff.name?ff.name:"forms["+c+"]";for(h=0;h<_IL(e);h++){if(e[h].type&&"hiddenbuttonsubmitimagereset".indexOf(e[h].type)<0&&d++>=f)break}if(d>=f){_fa=1;
for(h=0;h<_IL(e);h++){i=e[h];if(i.type&&"hiddenbuttonsubmitimagereset".indexOf(i.type)<0){i.lf=g+".";i.lf+=(i.name&&i.name!="")?i.name:"elements["+h+"]";
_EV(i,"focus",_FF)}}ff._FS=null;ff._FS=ff.onsubmit;if(_DD(ff._FS)&&ff._FS!=null){ff.onsubmit=_FO}else if(!(_bnN&&_bv<5)&&_hM&&!(_bnI&&!_I5)){if((!_bnI)||
(_II(navigator.userAgent,"Opera")>-1)){ff.onsubmit=_FO}else{_EV(ff,"submit",_FO);
eval("try{document.forms["+c+"]._FS=document.forms["+c+"].submit;document.forms["+c+"].submit=_FO;throw ''}catch(E){}")}}}}}
function _GR(a,b,c,d){if(!_D("hrf"))return a;if(_II(_hrf,"http",0)>-1)return _hrf;b=window.location.search;b=_IL(b)>1?_IS(b,1,_IL(b)):"";
c=_II(b,_hrf+"=");if(c>-1){ d=_II(b,"&",c+1);d=d>c?d:_IL(b);b=_IS(b,c+_IL(_hrf)+1,d)}return(b!=_hud&&_IL(b)>0)?b:a}
function _PO(a,b,c,d,e,f,g){d=location,e=d.pathname,f=_IS(e,_IF(e,"/")+1),g=document.title;if(a&&b==c){return(_pndef=="title"&&g!=""&&g!=d&&
!(_bnN&&_II(g,"http")>0))?g:f?f:_pndef}else{return b==c?(e==""||e=="/")?"/":_IS(e,(_ctdef!="full")?_IF(e,"/",_IF(e,"/")-2):_II(e,"/"),_IF(e,"/"))
:(b=="/")?b:((_II(b,"/")?"/":"")+(_IF(b,"/")==_IL(b)-1?_IS(b,0,_IL(b)-1):b))}}
function _PP(a,b,c,d){return ""+(c>-1?_PO(b,_IS(a,0,c),d)+";"+_PP(_IS(a,c+1),b,_II(_IS(a,c+1),";")):_PO(b,a,d))}
_mlc=_PP(_mlc,0,_II( _mlc,";"),"CONTENT+CATEGORY");_pn=_PP(_pn,1,_II(_pn,";"),"PUT+PAGE+NAME+HERE");
function _NN(a){return _D(a)!="none"}
function _E(a){var b="";var d=_IP(a,",");for(var c=0;c<_IL(d);c++)b+="&"+d[c]+"="+_A(_D(d[c]));return b}
function _F(a,b){return(!_II(a,"?"+b+"="))?0:_II(a,"&"+b+"=")}function _G(a,b,c,d){var e=_F(a,b);if(d&&e<0&&top&&window!=top){e=_F(_tls,b);
if(e>-1)a=_tls};return(e>-1)?_IS(a,e+2+_IL(b),(_II(a,"&",e+1)>-1)?_II(a,"&",e+1):_IL(a)):c}
function _H(a,b,c){if(!a)a=c;if(_I5||_N6){eval("try{_vv=_G(location.search,'"+a+"','"+b+"',1)}"+__c+"{}")}else{_vv=_G(location.search,a,b,1)}return unescape(_vv)}
function _I(a,b,c,d){__f=_IS(a,_II(a,"?"));if(b){if(_I5||_N6){eval("try{_hra=_G(__f,_hqsr,_hra,0)}"+__c+"{}")}else{_hra=_G(__f,_hqsr,_hra,0)}};
if(c&&!_hra){if(_I5||_N6){eval("try{_hra=_G(location.search,_hqsp,_hra,1)}"+__c+"{}")}else{_hra=_G(location.search,_hqsp,_hra,1)}};
if(d&&!_hra)_hra=d;return _hra}function _J(a,b,c,d){c=_II(a,"CP=");d=_II(a,b,c+3);return(c<0)?"null":_IS(a,c+3,(d<0)?_IL(a):d)}
var __r=".referrer",_rf=_A(eval("document"+__r)),_et=0,_oe=0,_we=0,_ar="",_hM=(!(_II(navigator.userAgent,"Mac")>-1)),_tls="";
_bv=parseInt(navigator.appVersion);_bv=(_bv>99)?(_bv/100):_bv;var __f,_hrat=_D("hra"),_hra="",__c="catch(_e)",_fa=0,_hlfs=0,_hoc=0,
_hlf='',_ce='',_ln='',_pl='',_bn=navigator.appName,_bn=(_II(_bn,"Microsoft")?_bn:"MSIE"),_bnN=(_bn=="Netscape"),_bnI=(_bn=="MSIE"),
_hck="*; path=/; "+(_D("cpd")&&_D("cpd")!=""?(" domain=."+_D("cpd")+"; "):"")+_ex,_N6=(_bnN&&_bv>4),_I5=false,_ss="na",_sc="na",_sv=11,_cy="u",_hp="u",
_tp=_D("ptc");if(_bn=="MSIE"){var _nua=navigator.userAgent,_is=_II(_nua,_bn),_if=_II(_nua,".",_is);if(_if>_is)_I5=_nua.substring(_is+5,_if)>=5}
if(_N6||_I5)eval("try{_tls=top.location.search}catch(_e){}")
function _PV(){_dcmpe=_H(_D("dcmpe"),_D("dcmpe"),"DCMPE");_dcmpre=_H(_D("dcmpre"),_D("dcmpre"),"DCMPRE");_vv="";_cmp=_H(_D("cmpn"),_D("cmp"),"CMP");
_gp=_H(_D("gpn"),_D("gp"),"GP");_dcmp=_H(_D("dcmpn"),_D("dcmp"),"DCMP");if(_II(_cmp,"SFS-")>-1){document.cookie="HBCMP="+_cmp+"; path=/;"+
(_D("cpd")&&_D("cpd")!=""?(" domain=."+_D("cpd")+"; "):"")+_ex}if(_bnI&&_bv>3)_ln=navigator.userLanguage;
if(_bnN){if(_bv>3)_ln=navigator.language;if(_bv>2)for(var i=0;i<_IL(navigator.plugins);i++)_pl+=navigator.plugins[i].name+":"};_cp=_D("cp");
if(location.search&&_TL(_cp)=="null")_cp=_J(location.search,"&");if(_II(document.cookie,"CP=")>-1){
_ce="y";_hd=_J(document.cookie,"*");if(_TL(_hd)!="null"&&_cp=="null"){_cp=_hd}else{document.cookie="CP="+_cp+_hck}}else{document.cookie="CP="+_cp+_hck;
_ce=(_II(document.cookie,"CP=")>-1)?"y":"n"};if(window.screen){_sv=12;_ss=screen.width+"*"+screen.height;_sc=_bnI?screen.colorDepth:screen.pixelDepth;
if(_sc==_hud)_sc="na"};_ra=_NA();if(_ra.toSource||(_bnI&&_ra.shift))_sv=13;if(!(_bnN&&_bv<5)&&!_bnI&&_hM)eval("try{throw _sv=14}catch(e){}");
if((new Date()).toDateString)_sv=15;if(_hbA.every)_sv=16;if(_I5&&_hM){if(_II(""+navigator.appMinorVersion,"Privacy")>-1)_ce="p";
if(document.body&&document.body.addBehavior){document.body.addBehavior("#default#homePage");_hp=document.body.isHomePage(location.href)?"y":"n";
document.body.addBehavior("#default#clientCaps");_cy=document.body.connectionType}};var _hcc=(_DD(_hcn))?_D("hcv"):"";if(!_D("gn"))_gn="ehg.hitbox.com";
if(_D("ct")&&!_D("mlc"))_mlc=_ct;_XT("PrePVR","");_ar=_GP()+_gn+"/HG?hc="+_mn+"&hb="+_A(_acct)+"&cd=1&hv=6&n="+_A(_pn,1)+"&con=&vcon="+_A(_mlc,1)+"&tt="
+_D("lt")+"&ja="+(navigator.javaEnabled()?"y":"n")+"&dt="+(new Date()).getHours()+"&zo="+(new Date()).getTimezoneOffset()+"&lm="+
Date.parse(document.lastModified)+(_tp?("&pt="+_tp):"")+_E((_bnN?"bn,":"")+"ce,ss,sc,sv,cy,hp,ln,vpc,vjs,hec,pec,cmp,gp,dcmp,dcmpe,dcmpre,cp,fnl")
+"&seg="+_D("seg")+"&epg="+_D("epg")+"&cv="+_A(_hcc)+"&gn="+_A(_D("hcn"))+"&ld="+_A(_D("hlt"))+"&la="+_A(_D("hla"))+"&c1="+_A(_D("hc1"))+"&c2="+
_A(_D("hc2"))+"&c3="+_A(_D("hc3"))+"&c4="+_A(_D("hc4"))+"&customerid="+_A(_D("ci")?_ci:_D("cid"))+"&ttt="+_lidt+","+_lpost;
if(_I5||_N6){eval("try{_rf=_A(top.document"+__r+")+''}"+__c+"{_rf=_A(document"+__r+")+''}")}
else{if(top.document&&_IL(parent.frames)>1){_rf=_A(eval("document"+__r))+""}else if(top.document){_rf=_A(eval("top.document"+__r))+""}}if((_rf==_hud)||
(_rf==""))_rf="bookmark";_rf=unescape(_rf);_rf=_GR(_rf);_hra=_I(_rf,_D("hqsr"),_D("hqsp"),_hrat);_ar+="&ra="+_A(_hra)+"&pu="+_A(_IS(eval("document.URL")
+"",0,_pum))+_hbSendEV()+"&rf=";_ar+=(_IL(_ar)+_IL(_rf)<2048)?_A(_rf):"bookmark";if(_IL(_ar)+_IL(_pl)<2048)_ar+="&pl="+_A(_pl);
_XT("PrePV",_ar);if(_D("onlyMedia")!="y")_hbi.src=_ar+"&hid="+Math.random();_hbq=_IS(_ar,0,_II(_ar,"&hec"));_XT("PostPV",_ar);_hbE=_NA()}_PV();
function _Q(a){a+="&hid="+Math.random();if(_hif==0){_hif=1;_hbs="";_hbs=new Image();_hbs.src=a}else{_hif=0;_hbi="";_hbi=new Image();_hbi.src=a}}
function __X(a){if(_ec==0){_ec=1;a=document;if(_NN("lt")||_NN("dlf")||_NN("elf"))_LP(a.links);if(_NN("fv"))_FA(a);
if(_NN("lt")&&_IL(_lvl)>0&&_lvl!=-1){_SV('lv.id',_lvid,1);_SV('lv.pos',_lvpos,1);_TV()}}}
function _EV(a,b,c,d){if(a.addEventListener){a.addEventListener(b,c,false)}else if(a.attachEvent){a.attachEvent(((d==1)?"":"on")+b,c)}}
function _EVO(e){return document.all?window.event.srcElement:this} 
function _RCV(a,b,c,d){b=document.cookie;c=_II(b,a+"=");d="";if(c>-1){d=_II(b,";",c+1);d=(d>0)?d:_IL(b);d=(d>c)?_IS(b,c+_IL(a)+1,d):""}return d}
function _RRV(a){return(_LVP(document.referrer,a))}function _RPV(a){return(_LVP(document.URL,a))}
function _XT(a,b){if(typeof _D("hbOn"+a)==_huf)eval("_hbOn"+a+"(b)")}
_EV(window,"load",__X);_EV(window,"unload",_FU);eval('setTimeout("__X()",3000)');

